3

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

How should I write the custom step?

Thanks

Leonardo Dario Perna
  • 1,045
  • 2
  • 10
  • 23

2 Answers2

3

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
jspooner
  • 10,975
  • 11
  • 58
  • 81
  • Also this line "tags.length.should eql(1)" could be cleaned up. It should be something like "tags.should have(1)" – jspooner Jul 20 '10 at 22:53
  • Note that this will only work for Cucumber + Webrat. If you are using Capybara, you will need to change `response.body` to `page.body`. – ndbroadbent Jan 27 '11 at 04:36
0

This is another way using capybara:

Then /^(?:|I )should see (\d+) images?$/ do |count|
  all("img").length.should == count.to_i
end
Zubin
  • 9,422
  • 7
  • 48
  • 52