How can I check one or more images on a page using Cucumber?

I want to check if 0, 1, 2 or 3 times has an image ('foo.png') on a specific page with a cucumber.

How to write a custom step?

thank

+3
source share
2 answers

You need to write a custom cucumber pitch that uses rspec custom match matches.

The sudo code will look something like this.

features / page.feature

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

functions / step_definitions / page_steps.rb

This file will use nokogiri to collect all the images with the given name, and then use rspec to check 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

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
+3

capybara:

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

Source: https://habr.com/ru/post/1755508/


All Articles