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’

module Capybara
  class Session
    def has_image?(src)
      has_xpath?("//img[contains(@src,\"/images/#{src}\")]")
    end
  end
end

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"
  end
end

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.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is a Developer Advocate for Kendo UI, a problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: WatchMeCode (screencasts), Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in Capybara, Rails, RSpec, Test Automation. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • GlyphGryph

    You might want to consider adding this to the Matchers module as well – while the Capybara Session can find it here, if you are looking within a certain element of the page this Matcher will magically cease to exist.

  • http://ivanenviroman.com ivanoats

    This is a nice helper. I had to change it slightly as some of my images are served from other paths, such as /logos etc…