3

我想用 Cucumber 测试某个页面中是否有 0、1、2 或 3 次图片('foo.png')。

我应该如何编写自定义步骤?

谢谢

4

2 回答 2

3

您需要编写一个使用自定义 rspec 期望匹配器的自定义黄瓜步骤。

sudo 代码看起来像这样。

特征/page.feature

Given I am on the images page
Then I should see 3 images

特征/step_definitions/page_steps.rb

该文件将使用 nokogiri 收集具有给定名称的所有图像,然后使用 rspec 验证您的期望。

Then /^I should see (.+) images$/ do |num_of_images|
   html = Nokogiri::HTML(response.body)
   tags = html.xpath('//img[@src="/public/images/foo.png"]')
   tags.length.should eql(num_of_images)
end

这是一个有效的 Rspec 示例,展示了如何将 Nokogiri 与 Rspec 一起使用

require 'nokogiri'

describe "ImageCount" do 

  it "should have 4 image" do
    html = Nokogiri::HTML('<html><body><div id=""><img src="/public/images/foo.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    </html></body>')
    tags = html.xpath('//img[@src="/public/images/foo.png"]')
    tags.length.should eql(4)
  end

  it "should have 3 image" do
    html = Nokogiri::HTML('<html><body><div id=""><img src="/public/images/bar.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    </html></body>')
    tags = html.xpath('//img[@src="/public/images/foo.png"]')
    tags.length.should eql(3)
  end

  it "should have 1 image" do
    html = Nokogiri::HTML('<html><body><div id=""><img src="/public/images/bar.png"></div>    <div id=""><img src="/public/images/aaa.png"></div>    <div id=""><img src="/public/images/bbb.png"></div>    <div id=""><img src="/public/images/foo.png"></div>    </html></body>')
    tags = html.xpath('//img[@src="/public/images/foo.png"]')
    tags.length.should eql(1)
  end

end
于 2010-07-20T19:21:16.590 回答
0

这是使用水豚的另一种方式:

Then /^(?:|I )should see (\d+) images?$/ do |count|
  all("img").length.should == count.to_i
end
于 2011-05-25T19:33:29.720 回答