From e589589e22322e8a90f4df1abfa9f442e15f4adf Mon Sep 17 00:00:00 2001 From: Thomas Walpole Date: Wed, 6 Apr 2016 10:59:11 -0700 Subject: [PATCH] add label selector --- lib/capybara/selector.rb | 21 +++++++++++++ lib/capybara/spec/session/selectors_spec.rb | 35 +++++++++++++++++++++ lib/capybara/spec/views/form.erb | 5 +++ 3 files changed, 61 insertions(+) create mode 100644 lib/capybara/spec/session/selectors_spec.rb diff --git a/lib/capybara/selector.rb b/lib/capybara/selector.rb index 1b7bf61a..6085f08a 100644 --- a/lib/capybara/selector.rb +++ b/lib/capybara/selector.rb @@ -354,6 +354,27 @@ Capybara.add_selector(:file_field) do end end +Capybara.add_selector(:label) do + label "label" + xpath do |locator| + xpath = XPath.descendant(:label) + xpath = xpath[XPath.string.n.is(locator.to_s) | XPath.attr(:id).equals(locator.to_s)] unless locator.nil? + xpath + end + + filter(:for) do |node, field_or_value| + if field_or_value.is_a? Capybara::Node::Element + if field_or_value[:id] && (field_or_value[:id] == node[:for]) + true + else + field_or_value.find_xpath('./ancestor::label[1]').include? node + end + else + node[:for] == field_or_value.to_s + end + end +end + Capybara.add_selector(:table) do xpath do |locator| xpath = XPath.descendant(:table) diff --git a/lib/capybara/spec/session/selectors_spec.rb b/lib/capybara/spec/session/selectors_spec.rb new file mode 100644 index 00000000..a467d626 --- /dev/null +++ b/lib/capybara/spec/session/selectors_spec.rb @@ -0,0 +1,35 @@ +Capybara::SpecHelper.spec Capybara::Selector do + before do + @session.visit('/form') + end + + describe ":label selector" do + it "finds a label by text" do + expect(@session.find(:label, 'Customer Name').text).to eq 'Customer Name' + end + + it "finds a label by for attribute string" do + expect(@session.find(:label, for: 'form_other_title')['for']).to eq 'form_other_title' + end + + it "finds a label from nested input using :for filter" do + input = @session.find(:id, 'nested_label') + expect(@session.find(:label, for: input).text).to eq 'Nested Label' + end + + it "finds the label for an non-nested element when using :for filter" do + select = @session.find(:id, 'form_other_title') + expect(@session.find(:label, for: select)['for']).to eq 'form_other_title' + end + + context "with exact option" do + it "matches substrings" do + expect(@session.find(:label, 'Customer Na', exact: false).text).to eq 'Customer Name' + end + + it "doesn't match substrings" do + expect { @session.find(:label, 'Customer Na', exact: true) }.to raise_error(Capybara::ElementNotFound) + end + end + end +end \ No newline at end of file diff --git a/lib/capybara/spec/views/form.erb b/lib/capybara/spec/views/form.erb index ef29ceb9..b92c41eb 100644 --- a/lib/capybara/spec/views/form.erb +++ b/lib/capybara/spec/views/form.erb @@ -333,6 +333,11 @@ New line after and before textarea tag + +