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

amjad picture amjad · Dec 14, 2012 · Viewed 75.6k times · Source

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 ?

Answer

pje picture pje · Dec 14, 2012

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"