Read more

Capybara: Find an element that contains a string

Henning Koch
November 21, 2016Software engineer at makandra GmbH

There is no CSS selector for matching elements that contains a given string ¹. Luckily, Capybara offers the :text option to go along with your selector:

page.find('div', text: 'Expected content')
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

You can also pass a regular expression!

page.find('div', text: /Expected contents?/i)

Note that if your CSS selector is as generic as div, you might get a lot more results than you expect. E.g. a <div class="container"> that surrounds your entire layout will probably also contain that text (in a descendant) and Capybara will return it. See Find the innermost DOM element that contains a given string.

Footnotes

¹ Only in jQuery selectors you can use the non-standard :contains Show archive.org snapshot to match elements containing a given piece of text.

Posted by Henning Koch to makandra dev (2016-11-21 18:54)