![](/img/trans.png)
[英]Rails: Given a String, check if an Array (of strings) contains a substring of String
[英]How to check if string contains all of strings in array?
我有
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"]
您可以简单地循环:
["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"]
尝试这个
["test@test.pl", "Email"].all?{ |str| last_email_sent.body[str] }.should == true
我喜欢将这样的数组放在实用程序方法中:
规格/支持/ 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
如果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(" ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.