diff --git a/lib/capybara/session.rb b/lib/capybara/session.rb index db7e2a55..87af683b 100644 --- a/lib/capybara/session.rb +++ b/lib/capybara/session.rb @@ -93,6 +93,13 @@ class Capybara::Session Capybara::SaveAndOpenPage.save_and_open_page(body) end + def find_field(locator, *kinds) + kinds = FIELDS_PATHS.keys if kinds.empty? + field = find_field_by_id(locator, *kinds) || find_field_by_label(locator, *kinds) + raise Capybara::ElementNotFound, "no field of kind #{kinds.inspect} with id or label '#{locator}' found" unless field + field + end + private def css_to_xpath(css) @@ -135,12 +142,6 @@ private button end - def find_field(locator, *kinds) - field = find_field_by_id(locator, *kinds) || find_field_by_label(locator, *kinds) - raise Capybara::ElementNotFound, "no field of kind #{kinds.inspect} with id or label '#{locator}' found" unless field - field - end - FIELDS_PATHS = { :text_field => proc { |id| "//input[@type='text'][@id='#{id}']" }, :text_area => proc { |id| "//textarea[@id='#{id}']" }, diff --git a/spec/session_spec.rb b/spec/session_spec.rb index 35fd0693..fa0d0b71 100644 --- a/spec/session_spec.rb +++ b/spec/session_spec.rb @@ -457,6 +457,31 @@ shared_examples_for "session" do end end + + describe '#find_field' do + before do + @session.visit('/form') + end + + it "should find any field" do + @session.find_field('Dog').value.should == 'dog' + @session.find_field('form_description').text.should == 'Descriptive text goes here' + @session.find_field('Region')[:name].should == 'form[region]' + end + + it "should raise an error if the field doesn't exist" do + running { + @session.find_field('Does not exist') + }.should raise_error(Capybara::ElementNotFound) + end + + it "should find only given kind of field" do + @session.find_field('form_description', :text_field, :text_area).text.should == 'Descriptive text goes here' + running { + @session.find_field('form_description', :password_field) + }.should raise_error(Capybara::ElementNotFound) + end + end describe '#within' do before do