remove_data_attributes
Motivation
As described in this post, using data attributes as selector makes your UI tests more resilient to change.
However, there is one little problem in this way: these attributes are useless when running your application in production.
Solution (with limitations)
remove_data_attributes is a plugin for Ruby on Rails like babel-plugin-react-remove-properties for Babel.
Note that the plugin can remove only the data attributes passed into the view helpers, because there is no room to parse and remove all attributes (including ones embedded in HTML tags) in advance unlike the Babel plugin.
Installation
Add this line to your application's Gemfile:
gem 'remove_data_attributes', group: :production
And then execute:
$ bundle
Usage
Run the installation generator with:
$ rails generate remove_data_attributes:install
And then specify data-*
attributes you'd like to remove in the generated configuration file:
data_attributes:
- data-testid
This will remove data-testid
attributes.
Example
Here is an example of removing data-testid
attributes.
Template
<%= form_with scope: :user, url: session_path(:user) do |f| %>
<%= field_set_tag "Email" do %>
<%= f.email_field :email, "data-testid": "email" %>
<% end %>
<%= field_set_tag "Password" do %>
<%= f.password_field :password, "data-testid" => "password" %>
<% end %>
<%= f.submit "Sign in", data: { testid: "submit" } %>
<% end %>
Rendered HTML (formatted for readability)
<form action="/users/sign_in" accept-charset="UTF-8" data-remote="true" method="post">
<input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="authenticity_token" value="HyOvLlyjIh7Sv7fFt2fKy5+uJNeKwnYobQPs49pl/H7CKSAVrw57jxpERJihR+B77GNSh2pZHG5mEWl0ieYQnQ==" />
<fieldset>
<legend>Email</legend>
<input type="email" value="" name="user[email]" />
</fieldset>
<fieldset>
<legend>Password</legend>
<input type="password" name="user[password]" />
</fieldset>
<input type="submit" name="commit" value="Sign in" data-disable-with="Sign in" />
</form>
Contributing
You should follow the steps below:
- Fork the repository
- Create a feature branch:
git checkout -b add-new-feature
- Commit your changes:
git commit -am 'Add new feature'
- Push the branch:
git push origin add-new-feature
- Send us a pull request
License
The gem is available as open source under the terms of the MIT License.