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:
The ‘contains’ function lets you specify the actual image name without having to worry about the junk at the end of the src attribute.