Test Selector Gem

In tests it can be hard to find the exact place where your expected results should be, because the results can be ambiguous. An option is to add selectors like id or class to elements so they can be found in tests.

But adding those selectors for tests doesn’t feel to well if they aren’t doing anything for you in production. Next to that it will get harder and harder to find new names that can be added as a selector and are unique on the page.

Therefore I created the gem test_selector to use with Ruby on Rails. With this gem the method test_selector is added to the ActionView and can be used as <%= test_selector() %>. This will add test-selector="_path_to_your_file_erb", a selector that will not show up in production.

This selector can be found in the tests by using:

describe "selector" do
  let(:path) { "path/to/your/file.erb" }

  scenario "find it" do
    selector = test_selector(path)

    expect(find_test_selector page.body, selector).to have_content "content"
  end
end

Next to that the test_selector in the ActionView has 2 arguments, name and value, that can be used to further specify your element. To find them in your tests they can be added as arguments to test_selector(path) as test_selector(path, name, value) corresponding with what is added to test_selector in the template.

Example using test_selector:

The usage of test_selector in path/to/your/file.erb

<h2 <%= test_selector("title") %>>title</h2>

<td <%= test_selector("name", user1.id) %>><%= user2.name %></td>
<td <%= test_selector("name", user2.id) %>><%= user2.name %></td>

Will turn into

<h2 test-selector="_path_to_your_file_erb__title">title<h2>

<td test-selector="_path_to_your_file_erb__name" test-value="1">name</td>

These can be found in the tests with:

describe "selector" do
  let(:path) { "path/to/your/file.erb" }


  scenario "find title and name of user 2" do
    create(:user)
    user2 = create(:user)
    title_selector = test_selector(path, "title")
    name_user_2 = test_selector(path, "name", user2.id)

    expect(find_test_selector page.body, title_selector).to have_content "title"
    expect(find_test_selector page.body, name_user_2).to have_content user2.name
  end
end

This gem is based on elixir test_selector that we use in our Elixir/Phoenix projects at DefactoSoftware.

rails  tests