【发布时间】:2011-05-26 03:33:29
【问题描述】:
我想用 Cucumber 在某个页面中测试我是否有 0、1、2 或 3 次图片('foo.png')。
我应该如何编写自定义步骤?
谢谢
【问题讨论】:
标签: ruby-on-rails ruby cucumber bdd webrat
我想用 Cucumber 在某个页面中测试我是否有 0、1、2 或 3 次图片('foo.png')。
我应该如何编写自定义步骤?
谢谢
【问题讨论】:
标签: ruby-on-rails ruby cucumber bdd webrat
您需要编写一个使用自定义 rspec 期望匹配器的自定义黄瓜步骤。
sudo 代码看起来像这样。
features/page.feature
Given I am on the images page
Then I should see 3 images
features/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
【讨论】:
response.body 更改为 page.body。
这是使用水豚的另一种方式:
Then /^(?:|I )should see (\d+) images?$/ do |count|
all("img").length.should == count.to_i
end
【讨论】: