Today I Learned

hashrocket A Hashrocket project

Find a Capybara node with regex

My pair and I faced a situation yesterday where we had to find a node with two separated pieces of text.

<section>
	<div>Something</div>
	<div>Some Other Text</div>
	<div>Apple</div>
</section>
<section>
  <div>Different</div>
  <div>Some Other Text</div>
  <div>Apple</div>
</section>
<section>
  <div>Something</div>
  <div>Some Other Text</div>
  <div>Orange</div>
</section>

We wanted to find a node with text "Something" and text "Orange" in our Capybara test.

The find method has a text option that you can pass a regex to.

find("section", text: /Something.*Orange/)

And initially this wasn't working because of a line break and so we had to use the multiline flag (m).

find("section", text: /Something.*Orange/m)
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.