Checking Invisible Elements

This week, I’m investing a bunch of hours on my side project. Today, I’m working on a feature where a field is supposed to remain invisible until a user enters a combination of values.

There are a variety of ways to test this code including testing the javascript with something like Jasmine. However, in this case, I particularly want an end-to-end test around this feature. And in my case that meant using Cucumber with Capybara for my end-to-end tests.

I wanted to be able to say something in my Cucumber .feature file like:

And I should not see the "My Notes" field

However, my first attempt at implementing didn’t work the way I expected it to. The “My Notes” field existed on the page but was hidden. When I called Capybara’s “has_css?” method, it found the field and reported it present. So my test was failing even though the system behavior did exactly what I wanted it to. Whoopsie!

So now what?

After two hours of wrestling with Capybara and CSS selectors, I finally found a solution that I can live with. And since I know other people have had this problem, I thought I would share it here.

But first, a note: this particular technique won’t work on elements that are given the display attribute of none directly through styles. It requires you to set display to none through a CSS class. (But setting attributes through CSS classes is a better design anyway, so I think this is a reasonable limitation.)

In my particular case, because I’m using jQuery, I’m using the .ui-helper-hidden class. You’ll need to figure out the class name that sets the display attribute to none for your application. The sample code below uses “.ui-helper-hidden” as the class name.

Here’s the helper method that I came up with:

(If you have javascript disabled, you might not see the beautifully formatted gist from github above. In that case, you can see the helper method if you click here.)

I hope that little helper method saves someone some time. If so, it was totally worth the 2 hours I spent today figuring out how to write it.