【问题标题】:Cucumber scenario searching in a file using ruby使用 ruby​​ 在文件中搜索黄瓜场景
【发布时间】:2012-01-06 07:04:16
【问题描述】:

我有一个黄瓜场景,它检查文件中的某些字符串。这不是一种非常理想的做事方式,但它已被视为绝对需要。

我的 Cucumber 场景有一张桌子:

电子邮件应该有

|search_string|
|Nokogiri     |
|Cucumber     |
|White Tiger  |

我的步骤定义

Given /^the email should have$/ do |table|
  table.hashes.each do |hash|
    check_email(hash["search_string"])
  end
end

我的 check_email 方法

require 'nokogiri'

def check_email(search_string)
  htmlFile = File.open(filename).read
  doc = Nokogiri::HTML::DocumentFragment.parse(htmlFile)
  if (doc.content["#{search_string}"])
    puts true
    return true
  end
  htmlFile.close
  puts false
  return false
end

我正在阅读的文件虽然是“.txt”文件扩展名,但文件中的内容是 HTML 格式。

  1. 方法正在读取正确的文件
  2. 该文件包含该方法试图定位的内容

现在是我看到的实际问题。

  1. 我的黄瓜场景中的 search_string 有 3 个要搜索的值。文件中没有“白虎”
  2. 因为“白虎”不在文件中,所以测试应该失败,而是测试通过/我应该说我看到“绿色”,并且当我在代码中输出上述实际结果时,它清楚地显示(对于Nokogiri,对 Cucumber 为 true,对 White Tiger 为 false)。

我的问题是我该怎么做。 Cucumber 表结果应该只对文件中可用的值显示 GREEN/PASS,对文件中没有的值显示 RED/FAIL。

有人可以帮我解决这个问题吗?提前欣赏。

【问题讨论】:

    标签: file-io cucumber


    【解决方案1】:

    除非引发异常,否则 Cucumber 不会失败一步(这是当 RSpec 匹配器不满足时会发生的情况)。简单地返回 true 或 false 是没有意义的。

    你的断言应该看起来像

    if (!doc.content["#{search_string}"])
        raise "Expected the file to contain '#{search_string}'"
    end
    

    【讨论】:

    • 如果我或 undees 的回答对您有所帮助,请考虑投票并将其中一个标记为已接受,谢谢!
    【解决方案2】:

    如果您想按原样使用您的check_email 函数,您可以在步骤定义中添加一个断言:

    Given /^the email should have$/ do |table|
      table.hashes.each do |hash|
        check_email(hash["search_string"]).should be_true
      end
    end
    

    你也可以让你的电子邮件函数返回一个字符串,并在你的步骤定义中检查它的内容:

    require 'nokogiri'
    
    def email_contents
      html = IO.read(filename)
      doc  = Nokogiri::HTML::DocumentFragment.parse(html)
      return doc.content
    end
    
    # ...
    
    Given /^the email should have$/ do |table|
      contents = email_contents
    
      table.hashes.each do |hash|
        contents.should include(hash["search_string"])
      end
    end
    

    这些并不比 Jon M 的方法更好或更差——只是另一种选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      相关资源
      最近更新 更多