开发者

How can I test one, more or none images in a page with Cucumber?

开发者 https://www.devze.com 2023-01-08 14:33 出处:网络
I want to test if I have 0, 1, 2 or 开发者_Go百科3 times a pictures (\'foo.png\') in a certain page with Cucumber.

I want to test if I have 0, 1, 2 or 开发者_Go百科3 times a pictures ('foo.png') in a certain page with Cucumber.

How should I write the custom step?

Thanks


You need to write a custom cucumber step that uses a custom rspec expectation matcher.

The sudo code would look something like this.

features/page.feature

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

features/step_definitions/page_steps.rb

This file would use nokogiri to collect all the images with a given name and then use rspec to validate your expectation.

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

Here is a working Rspec example that shows how to use Nokogiri with 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


This is another way using capybara:

Then /^(?:|I )should see (\d+) images?$/ do |count|
  all("img").length.should == count.to_i
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号