2

我在 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 步骤中做到这一点?

4

3 回答 3

3

无需使用 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 
于 2012-04-12T08:02:31.810 回答
2

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

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

我没有尝试过这个来确保给定的路径File.exists?是正确的。但是,如果您首先在测试中将其打印出来,您会看到它的外观以及是否需要对其进行一些修改。

于 2012-04-11T16:09:32.667 回答
1

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

if find('img.avatar')[:naturalWidth] == 0
  raise('image broken')
end
于 2012-04-12T03:00:08.567 回答