Find elements by data attributes

The answer given by Justin Ko is correct, I just wanted to add something slightly more advanced which can help with test readability in some situations. You can add your own "selectors" to Capybara, so if you really wanted to select things by a data-test attribute (not a great idea since you don't really want to be adding attributes just for testing) a lot you could do

Capybara.add_selector(:dt) do
  css { |v| "*[data-test=#{v}]" }

which would allow

find(:dt, 'edit.update')

this can make tests understandable while also limiting complicated css or path queries to a single place in your test code. You can then define a method such as

def find_by_dt(value)
 find(:dt, value)

if you prefer the look of find_by_dt...) to find(:dt, ...)

You can also add filters and descriptions to your own selections for more flexibility, better error descriptions, etc - see for the built-in selectors provided by capybara

To locate elements by their data-* attribute, you need to use a CSS-selector or XPath.

For the CSS-selector:


For XPath:


Whether or not it is a good idea really depends on the application. You want to pick something that uniquely identifies the element. If "edit.update" is not going to be unique, it would not be a good choice to use. The class attribute would be fine if the button had a unique class, which "button" and "last" are not likely to be.

The best approach is really to use static id attributes as they should be unique within the page and are less likely to change. The find method also supports locating elements by id, which means you do not have to write CSS-selectors or XPath.