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 Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)