Phil Phil - 4 months ago 22
CSS Question

How to adjust Capybara finders on a site using css-modules?

In our automated tests, a typical line in our code might look something like:

find('.edit-icon').click


We're on our way to using css-modules in our project and I've been warned that class names may change dramatically. A pretty zany example is this site that uses emojis in its class names (when you inspect the page):

css modules by Glenn Maddern

How might I best prepare for a change this drastic? I imagine many of our specs breaking, but I am a little worried about being unable to write tests at all with this new technology in our project.

Answer

Using custom capybara selectors you can abstract away from the actual css query being done and move it to one location. In your comments you mentioned the need to change to a class attribute that begins with a passed in value.

Capybara.add_selector(:class_starts_with) do
  css { |locator| "[class^=\"#{locator}\"]"
end

would do that and then can be called as

find(:class_starts_with, 'something')

or if you set Capybara.default_selector = :class_starts_with it would just be

find('something')

Rather than changing default_selector another option would be to just define a helper method like find_by_class_start or something that just calls find with :class_starts_with passed (how Capybara's #find_field, etc work).

Also note the custom selector above would only really work if only one class name was set, if multiple are expected you could change the selector to "[class^=\"#{locator}\"], [class*=\" #{locator}\"]"

Comments