Search⌘ K
AI Features

Use data-testid Attributes to Combat Brittle Tests

Understand how to use data-testid attributes in Ruby on Rails view tests to create more stable and maintainable system tests. Explore strategies to reduce test breakage caused by semantic HTML changes and maintain consistent test selectors.

We'll cover the following...

The tags used in our view are currently semantically correct, and thus, our tests can safely rely on that. However, these semantics might change without affecting the way the page actually works. Suppose we want a new message, “Widget Information,” on the page as the most important thing. That means our widget name should no longer be an <h1>, but instead an <h2>.

Here’s the change to update the view:

HTML
<%# app/views/widgets/show.html.erb %>
→ <h1>Widget Information</h1>
→ <h2><%= @widget.name %></h2>

This change will break our tests even though the change didn’t affect the functionality of the feature:

Shell
bin/rails test test/system/view_widget_test.rb || echo Test \
Failed
Running 1 tests in a single process (parallelization thresho…
Run options: --seed 17881
# Running:
Failure:
ViewWidgetTest#test_we_can_see_a_list_of_widgets_and_view_on…
expected to find visible css "h1" with text /stembolt/i but …
rails test test/system/view_widget_test.rb:4
Finished in 1.649222s, 0.6063 runs/s, 1.8190 assertions/s.
1 runs, 3 assertions, 1 failures, 0 errors, 0 skips
Test Failed

We can see what’s broken, but the best way to fix it is not clear. If we change the tag name used in ...