How to find an element by matching exact text of the element in Capybara

RubyRegexCapybara

Ruby Problem Overview


I have following two elements in HTML

<a href="/berlin" >Berlin</a>
<a href="/berlin" >Berlin Germany </a>

I am trying to find the element by using following Capybara method

find("a", :text => "berlin")

Above will return two elements because both contains text berlin.

Is there a way to match exact text in Capybara ?

Ruby Solutions


Solution 1 - Ruby

Use a regexp instead of a string for the value of the :text key:

find("a", :text => /\ABerlin\z/)

Check out the 'Options Hash' section of the Method: Capybara::Node::Finders#all documentation.

PS: text matches are case sensitive. Your example code actually raises an error:

find("a", :text => "berlin")
# => Capybara::ElementNotFound:
#    Unable to find css "a" with text "berlin"

Solution 2 - Ruby

Depending on which version of the gem you are using

find('a', text: 'Berlin', exact: true)

may be deprecated. In which case you would have to use

find('a', text: 'Berlin', match: :prefer_exact)

Solution 3 - Ruby

You can do so too:

find('a', text: 'Berlin', exact_text: true)

That will find for CSS.

And using only exact: true instead of exact_text will show you a msg that exact option is only valid for XPATH.

Solution 4 - Ruby

Just use Capybara's exact option:

Capybara.exact = true

Solution 5 - Ruby

My preference is to use the have_selector with text and exact_text: true:

expect(body).to have_selector 'a', text: 'Berlin', exact_text: true

Solution 6 - Ruby

For using click_link in capybara you need to add one more property in the method using it.

click_link(link_name, :text => link_name)

Here the link_name is the text value of a link. Using :text keyword we are specifying that we want to click on a link having the text value which is exact matching to our requirement.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamjadView Question on Stackoverflow
Solution 1 - RubypjeView Answer on Stackoverflow
Solution 2 - RubyGabriel PumpleView Answer on Stackoverflow
Solution 3 - RubyCamiloVAView Answer on Stackoverflow
Solution 4 - RubyJohn WView Answer on Stackoverflow
Solution 5 - RubyPaweł GościckiView Answer on Stackoverflow
Solution 6 - RubySunil KumarView Answer on Stackoverflow