【问题标题】:How can I test one, more or none images in a page with Cucumber?如何使用 Cucumber 在页面中测试一个、多个或没有图像?
【发布时间】:2011-05-26 03:33:29
【问题描述】:

我想用 Cucumber 在某个页面中测试我是否有 0、1、2 或 3 次图片('foo.png')。

我应该如何编写自定义步骤?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby cucumber bdd webrat


    【解决方案1】:

    您需要编写一个使用自定义 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
    

    【讨论】:

    • 这一行“tags.length.should eql(1)”也可以被清理。它应该类似于“tags.should have(1)”
    • 请注意,这只适用于 Cucumber + Webrat。如果您使用 Capybara,则需要将 response.body 更改为 page.body
    【解决方案2】:

    这是使用水豚的另一种方式:

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

    【讨论】:

      猜你喜欢
      • 2015-09-29
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      相关资源
      最近更新 更多