我想测试我是否在某个黄瓜页面上有0,1,2或3次图片('foo.png')。
我该如何编写自定义步骤?
由于
答案 0 :(得分: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
答案 1 :(得分:0)
这是使用水豚的另一种方式:
Then /^(?:|I )should see (\d+) images?$/ do |count|
all("img").length.should == count.to_i
end