如何检查字符串是否包含数组中的所有字符串?

时间:2013-04-16 09:11:10

标签: ruby-on-rails ruby rspec matcher

我有

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"]

4 个答案:

答案 0 :(得分:3)

你可以简单地循环:

["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"]

答案 1 :(得分:1)

试试这个

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

答案 2 :(得分:1)

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

<强>规格/支持/ utilities.rb

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

<强>规格/ your_spec.rb

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

答案 3 :(得分:0)

如果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(" ")