如何在 Rails 3 中使用 Cucumber/Capybara 找到页面上的图像 [英] How do I find an image on a page with Cucumber / Capybara in Rails 3
问题描述
我正在使用带有 Rails 3 的 Cucumber/Capybara 并尝试在上传后验证图像的存在.我不确定如何检查图像的 url 来验证它.
I am using Cucumber / Capybara with Rails 3 and am trying to validate the existence of an image after upload. I'm not sure how to check the url of the image to validate it.
我有以下场景:
Scenario: Create new listing
Given I am on the new listing page
When I fill in "listing_name" with "Amy Johnson Photography"
And I attach the file "features/support/test_image.jpg" to "listing_images_attributes_0_photo"
And I press "Create"
Then I should see "Amy Johnson Photography"
And I should see the image "test_image.jpg"
除了最后一步,一切都通过了.
Everything passes except the last step.
我已经为我的步骤定义尝试了这个,如果它是页面上的文本,它会很好,但不适用于图像 url:
I've tried this for my step definition, which works great if it's text on the page, but doesn't for an image url:
Then /^I should see the image "(.+)"$/ do |image|
if page.respond_to? :should
page.should have_content(image)
else
assert page.has_content?(image)
end
end
然后我也尝试了类似这个步骤定义的东西:
Then I've also tried something like this step definition instead:
Then /^I should see the image "(.+)"$/ do |image|
html = Nokogiri::HTML(response.body)
tags = html.xpath('//img[@src="/public/images/foo.png"]')
# tags.length.should eql(num_of_images)
end
导致以下错误:
And I should see the image "test_image.jpg" # features/step_definitions/listing_steps.rb:41
undefined method `body' for nil:NilClass (NoMethodError)
./features/step_definitions/listing_steps.rb:42:in `/^I should see the image "(.+)"$/'
features/manage_listings.feature:24:in `And I should see the image "test_image.jpg"'
我假设您需要一个 nokogiri 步骤才能正确找到它.或者如果有更好的方法,我愿意接受建议.如何验证我刚刚上传的图片是否在页面上?谢谢.
I'm assuming you need a nokogiri step to find this properly. Or if there's a better way, I'm open to suggestions. How can I validate that the image I just uploaded is on the page? Thanks.
推荐答案
Nokogiri 的解决方案应该可以正常工作.唯一的问题是 Cabybara API 与 Webrat 不同,因此您必须使用 page.body
而不是 response.body
.
The solution with Nokogiri should work fine. The only problem is that the Cabybara API is different to Webrat, so instead of response.body
, you must use page.body
.
但还有一种更好的方法来使用 Cabybara 测试图像:
But theres an even better way to test for the image with Cabybara :
Then /^I should see the image "(.+)"$/ do |image|
page.should have_xpath("//img[@src="/public/images/#{image}"]")
end
这篇关于如何在 Rails 3 中使用 Cucumber/Capybara 找到页面上的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!