When writing browser tests in Rails with capybara, sometimes you’ll need to find an element based on an HTML attribute. A common use-case is when an element is explicitly marked with data-testid to make it easier to find in automated tests.
Consider this markup:
Let’s say we want to write an assertion about the text contained in that card. We can use the data-testid to find it.
This works, but the syntax is not ideal: it requires a mixture of nested single- and double-quotes, plus square brackets that must be placed just so, and it is not particularly easy to read.
Thankfully Capybara’s find method has a better way to write this, which I’ll explain next.
The find method in Capybara is a lot more capable than it appears at first glance. By default, it accepts a CSS expression, but other strategies are available:
The :element strategy is one that works particular well to find HTML attributes like data-testid. Here’s how to use it:
This looks more like idiomatic Ruby. It’s easier to read and write than CSS and xpath expressions, which always feel a bit out of place within Ruby code. The syntax is also familiar because it is similar to Rails tag helpers.
Of course, the :element selector strategy is not limited to data-testid.
Hi! 👋 I’m Matt Brictson, a software engineer in San Francisco. This site is my excuse to practice UI design,
fuss over CSS, and share my interest in open source. I blog about Rails, design patterns, and other