如何在Rails 3中使用Cucumber / Capybara在页面上找到图像
我正在使用Cucumber / Capybara和Rails 3,我试图在上传后validation图像的存在。 我不知道如何检查图像的url来validation它。
我有以下情况:
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"
除了最后一步,一切都过去了。
我已经尝试过这个用于我的步骤定义,如果它是页面上的文本,则效果很好,但不适用于图像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 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步骤来正确找到它。 或者如果有更好的方法,我愿意接受建议。 如何validation我刚上传的图片是否在页面上? 谢谢。
Nokogiri的解决方案应该可以正常工作。 唯一的问题是Cabybara API与Webrat不同,因此您必须使用page.body
而不是response.body
。
但是有一种更好的方法来测试Cabybara的图像:
Then /^I should see the image "(.+)"$/ do |image| page.should have_xpath("//img[@src=\"/public/images/#{image}\"]") end
嗨,我不熟悉XPATH,但使用CSS你可以尝试:
如果page.respond_to? :应该 page.should have_selector(“img [src $ ='#{imagename}']”) 其他 assert page.has_selector?(“img [src $ ='#{imagename}']”) 结束
希望有所帮助 jramby
您可以通过这种方式测试它,也不依赖于路径:
Then /^I should see the image "(.+)"$/ do |image| page.should have_xpath("//img[contains(@src, \"#{image}\")]") end
page.should
现已弃用。 请改用
期待(页)。为了
完整示例:
Then /^I should see the image "(.+)"$/ do |image| expect(page).to have_xpath("//img[contains(@src, \"#{image}\")]") end
这有用吗?
page.should have_xpath('//img[@src="/public/images/foo.png"]')
是的,但这些xpath测试不会处理……
/public/images/foo.jpg public/images/foo.jpg http://sofzh.miximages.com/ruby-on-rails/foo.jpg
…都是与图像相同的有效链接。
如果你有很多你想测试的图像,你可以创建一个has_image吗? Capybara的匹配器。
这很容易,这篇文章一步一步解释: 添加has_image? 匹配给Capybara
这个语法对我有用,而且更具可读性。
page.should have_css(“img”,:src =>“/ public / images / foo.png”)