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

问题描述:

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

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

而且我想用数组

last_email_sent.body.should include ["[email protected]", "Email"] 
+0

是什么'last_email_sent.body'样子? –

+0

它是多串 – tomekfranek

你可以简单地循环:

["[email protected]", "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 ["[email protected]", "Email"] 
+0

注的第一份工作没工作,'| include_items |'输入需要去对整个匹配定义 –

+0

我想弄清楚如何扭转这种匹配到''不应该包括any'' – tomekfranek

+1

@regedarek:主要是你需要注意的双重否定。刚刚实施新的匹配include_any(因为'should_not include_all'不一样'应该include_any'),使'failure_message_for_should_not'是比我上面一点更加有用。提示:你不能在正数情况下使用@errors数组,所以'match'模块应该非常简单。 。 。 –

试试这个

["[email protected]", "Email"].all?{ |str| last_email_sent.body[str] }.should == true 
+0

那么也许吸尘器将是:''be_in_body.each {|串| last_email_sent.body.should包括字符串}'' – tomekfranek

+0

@regedarek,是的,你_should_是正确的:) – fl00r

如果last_email_sent.body正是Company Name SomeCompany [email protected] Email取代它:

last_email_sent.body.should include ["Company Name", "SomeCompany", "[email protected]", "Email"].join(" ") 

我喜欢把阵列一样,在一个实用方法:

规格/支持/ utilities.rb

def email_body_elements 
    ["Company Name", "Some Company", "Email", "[email protected]"] 
end 

规格/ your_spec.rb

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