如何在Rails 3中使用Cucumber/Capybara在页面上找到图像

Jam*_*les 23 ruby-on-rails paperclip cucumber

我正在使用Cucumber/Capybara和Rails 3,我试图在上传后验证图像的存在.我不确定如何检查图像的URL来验证它.

我有以下场景:

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"
Run Code Online (Sandbox Code Playgroud)

除了最后一步,一切都过去了.

我已经尝试过这个用于我的步骤定义,如果它是页面上的文本,则效果很好,但不适用于图像网址:

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
Run Code Online (Sandbox Code Playgroud)

然后我也尝试了类似这个步骤的定义:

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
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

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"'
Run Code Online (Sandbox Code Playgroud)

我假设您需要一个nokogiri步骤来正确找到它.或者,如果有更好的方法,我愿意接受建议.如何验证我刚上传的图片是否在页面上?谢谢.

ndb*_*ent 39

Nokogiri的解决方案应该可以正常工作.唯一的问题是Cabybara API与Webrat不同,所以不必response.body使用page.body.

但是有一种更好的方法来测试Cabybara的图像:

Then /^I should see the image "(.+)"$/ do |image|
    page.should have_xpath("//img[@src=\"/public/images/#{image}\"]")
end
Run Code Online (Sandbox Code Playgroud)


jra*_*mby 13

嗨,我不熟悉XPATH,但使用CSS,你可以尝试:

  if page.respond_to? :should
    page.should have_selector("img[src$='#{imagename}']")
  else
    assert page.has_selector?("img[src$='#{imagename}']")
  end

希望有所帮助 jramby

  • 这也有效:`page.should have_css("img [src $ ='#{imagename}']")` (3认同)

Pau*_*aka 6

您可以通过这种方式测试它,也不依赖于路径:

Then /^I should see the image "(.+)"$/ do |image|
    page.should have_xpath("//img[contains(@src, \"#{image}\")]")
end
Run Code Online (Sandbox Code Playgroud)


Noé*_*her 5

page.should

现已弃用.请改用

期待(页).为了

完整示例:

Then /^I should see the image "(.+)"$/ do |image|
    expect(page).to have_xpath("//img[contains(@src, \"#{image}\")]")
end
Run Code Online (Sandbox Code Playgroud)