簡體   English   中英

如何檢查字符串是否包含數組中的所有字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM