Phil Phil - 1 year ago 119
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:


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 Source

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}\"]"

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


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}\"]"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download