【问题标题】:How to check if string contains all of strings in array?如何检查字符串是否包含数组中的所有字符串?
【发布时间】:2013-04-16 09:11:09
【问题描述】:

我有

last_email_sent.body.should include "Company Name"
last_email_sent.body.should include "SomeCompany"
last_email_sent.body.should include "Email"
last_email_sent.body.should include "test@test.pl"

我想用数组替换它

last_email_sent.body.should include ["test@test.pl", "Email"]

【问题讨论】:

  • last_email_sent.body 长什么样子?
  • 多行字符串

标签: ruby-on-rails ruby rspec matcher


【解决方案1】:

你可以简单地循环:

["test@test.pl", "Email"].each { |str| last_email_sent.body.should include str }

或者如果你喜欢匹配器语法,写你自己的匹配器:

RSpec::Matchers.define :include_all do |include_items|
  match do |given|
    @errors = include_items.reject { |item| given.include?(item) }
    @errors.empty?
  end

  failure_message_for_should do |given|
    "did not include \"#{@errors.join('\", \"')}\""
  end

  failure_message_for_should_not do |given|
     "everything was included"
  end

  description do |given|
    "includes all of #{include_items.join(', ')}"
  end
end

像这样调用它:

last_email_sent.body.should include_all ["test@test.pl", "Email"]

【讨论】:

  • 注意第一次发帖无效,|include_items| 输入需要在整个匹配器定义上进行
  • 我想弄清楚如何将该匹配器反转为should not include any
  • @regedarek:主要是你需要注意双重否定。只需实现一个新的匹配器 include_any(因为should_not include_allshould include_any 不同),并使failure_message_for_should_not 比我上面做的更有用。提示:您将无法在肯定情况下使用 @errors 数组,因此 match 块应该非常简单。 . .
【解决方案2】:

试试这个

["test@test.pl", "Email"].all?{ |str| last_email_sent.body[str] }.should == true

【讨论】:

  • 那么更清洁的可能是:be_in_body.each {|string| last_email_sent.body.should include string}
【解决方案3】:

我喜欢将这样的数组放入实用程序方法中:

spec/support/utilities.rb

def email_body_elements
  ["Company Name", "Some Company", "Email", "test@test.pl"]
end

spec/your_spec.rb

email_body_elements.each do |element|
  last_email_sent.body.should include element
end

【讨论】:

    【解决方案4】:

    如果last_email_sent.body 正好是Company Name SomeCompany test@test.pl Email

    last_email_sent.body.should include ["Company Name", "SomeCompany", "test@test.pl", "Email"].join(" ")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 2015-09-08
      • 2023-04-01
      • 2019-06-07
      • 1970-01-01
      • 2010-11-16
      • 2021-06-10
      相关资源
      最近更新 更多