How to test if an img tag points to an existing image?

I'm using Cucumber and Capybara for BDD on a RoR application. I have the following feature

Feature: List profiles
  In order to know that the people behind the profiles are real people 
  As a lurker
  I want to be able to find who is registed and see their profile picture

Background: Profiles have been added to the database, some with picture attached
  Given some profiles exist
  And  I am on the home page

Scenario: Search by city, avatars should be there
  When I search for a city with profiles
  Then I should see some result profiles with avatar

The underlying Capybara steps file contains:

Then /^I should see some result profiles with avatar$/ do
  page.should have_css("#profile_search_results .profile img.avatar", :count => some_profiles)

This step checks that the page contains

<div id="#profile_search_results>
  <img class="avatar" src="" />

BUT... I also want to check if the image exists (it is not a broken image).

How can I do this in my Capybara steps?


The way to check, without having to use Selenium or any other drivers, was to extract the src attribute from the img element (Thanks MrDanA), and check the status code after visiting that URL:

page.should have_css("#profile_search_results .profile img.avatar", :count => some_profiles)
img = page.first(:css, "#profile_search_results .profile img.avatar")
visit img[:src]
page.status_code.should be 200 

You can use Capybara's finder methods to find the img tag in question, then get it's src attribute (e.g src = element[:src]). Then you can use Ruby to see if it exists. So all in all it would look something like this:

element = page.first(:css, "...")
src = element[:src]
assert File.exists?("#{Rails.root}/#{src}")

I haven't tried this to make sure the path given to File.exists? is right. But if you print it out first in a test, you'll see what it looks like and whether or not you need to tinker with it a bit.

Assuming the test is running in Firefox, you can check the naturalWidth property of the image. If it is 0, the image is broken.

if find('img.avatar')[:naturalWidth] == 0
  raise('image broken')

Need Your Help

C++ program works on XP SP2 only after installing Visual Studio

c++ visual-studio winapi windows-xp

I have a C++ program. It's quite simple - shows an image (splash screen) and launches another application, then closes when that other application is started. Actually, this one: http://www.olsonso...

Rails - How do I update multiple records via a form from the list action?

ruby-on-rails ruby-on-rails-3 activerecord

I'm trying to update one field of multiple records in a model, Lead. Each lead is displayed in a table row, and the field being modified for the multiple rows is "selected", which is a boolean, sto...