Adding A ‘has_image?’ Matcher To Capybara


I’m rather shocked that Capybara doesn’t have a ‘has_image?’ matcher built in to it. But after search around google for a while, the only thing I found was a bunch of StackOverflow answers that all say to use ‘has_xpath?’ to find the image. How painful is that?! So, here’s my implementation of a ‘has_image?’ matcher.

Drop this into ‘/features/support/has_image.rb’

Then you can run code like this in your cucumber steps, and it will look for the image based on the ‘src’ attribute, and assuming a ‘/images/’ path for your images.

Note that I’m using the magic rspec matchers to go from “.should have_image” to the “.has_image?” method that I just added.

Also note that I made use of the ‘contains’ xpath function in my matcher. This is because Rails likes to put gibberish at the end of image paths, to enable caching, etc:

Screen Shot 2011 09 27 at 4 27 14 PM

The ‘contains’ function lets you specify the actual image name without having to worry about the junk at the end of the src attribute.

← SEO And Accessibility With HTML5 PushState, Part 2: Progressive Enhancement With Backbone.js
JavaScript Has Built-In Mix-ins With ‘apply’ Or ‘call’ →