ruby-on-railstestingrspeccapybaracapybara-webkit

Find elements by data attributes


I'm improving my tests with RSpec and capybara-webkit, trying to delete all the css and xpath selectors like

find('#edit_user > div:nth-child(7) > div > div > button').click

and I'm looking for the best option to replace them.

I was going to use the css class of the elements but some "pro" capybara tester said this is not the best option.

So my question is: can I use the dataattributes in my tests?
If I have an element

<button name="button" type="submit" class="button last" data-test="edit.update">Update/button>

will I be able to do

find('edit.update').click

?

And do you think it is a good idea? If you have more ideas/infos about this topic, feel free to comment!


Solution

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

    For the CSS-selector:

    find('button[data-test="edit.update"]').click
    

    For XPath:

    find('//button[@data-test="edit.update"]').click
    

    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.