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’
module Capybara class Session def has_image?(src) has_xpath?("//img[contains(@src,\"/images/#{src}\")]") end endend
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.
Then /^the biometrics section should be marked incomplete$/ do within "#assessment-menu" do page.should have_image "warning_24.png" endend
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.
