如何测试img标记是否指向现有图像?

时间:2012-04-11 16:03:49

标签: ruby-on-rails cucumber capybara

我在RoR应用程序上使用Cucumber和Capybara进行BDD。我有以下功能

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

底层的Capybara步骤文件包含:

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

此步骤检查页面是否包含

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

但是......我还想检查图像是否存在(它不是图像损坏)。

我如何在Capybara步骤中执行此操作?

3 个答案:

答案 0 :(得分:2)

在不必使用Selenium或任何其他驱动程序的情况下检查的方法是从img元素中提取src属性(感谢MrDanA),并在访问该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 

答案 1 :(得分:1)

您可以使用Capybara的finder方法查找有问题的img标记,然后获取src属性(例如src = element[:src])。然后你可以使用Ruby来查看它是否存在。总而言之,它看起来像这样:

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

我没有尝试过这个来确保File.exists?的路径是正确的。但是如果你在测试中首先将它打印出来,你会看到它的样子以及你是否需要修补它。

答案 2 :(得分:0)

假设测试在Firefox中运行,您可以检查图像的naturalWidth属性。如果为0,则图像被破坏。

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