[LRUG] Test presence of image on page with Selenium

Jake Prime jake at team-prime.com
Thu Mar 10 09:01:45 PST 2016


Hello!

I am trying to test that a specific image is present on a page. I'd like to
be able to write something like this:

*expect(page).to have_image 'img.logo', file: '/path/to/logo/file.jpg'*

I don't want to test the value of the src attribute, I want to actually
load the file and do a binary comparison with a copy of the same image. In
my current Cucumber scenario there is a logo on a page, I have now uploaded
a new logo and would like to check the correct image is being displayed.

I have been able to get this working using Capybara::Session#save_page as
follows:

*def has_image?(selector, options = {})*
*  image_path = find(selector)[:src]*

*  original_path = current_path*
*  visit **image_path*
*  match = IO.read(save_page) == IO.read(options[:file])*
*  visit original_path*
*  match*
*end*

This works just fine with the default driver (although in an ideal world
I'd rather not navigate off the current page and back). But it does not
work with Selenium, as when you visit an image file Firefox creates a
default HTML surround page to embed the image, and therefore this is what
is saved and compared.

I tried using OpenURI, and got pretty close with this:

*file_contents = open(options[:file]) { |f| f.read }*
*web_contents = open(**image_path**) { |f| f.read }*
*match = file_contents == web_contents*

But it fails as it is comparing what appears to be a different character
encoding:

file_contents[0..30]
\xFF\xD8\xFF\xE1\u001EWExif\u0000\u0000II*\u0000\b\u0000\u0000\u0000\u0010\u0000\u0000\u0001\u0003\u0000\u0001\u0000\u0000\u0000\xC0

web_contents[0..30]
\xFF\xD8\xFF\xE1\x1EWExif\x00\x00II*\x00\b\x00\x00\x00\x10\x00\x00\x01\x03\x00\x01\x00\x00\x00\xC0


Can anyone help with this method, or suggest a better one?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20160310/768bb8f2/attachment.html>


More information about the Chat mailing list