Rails minitest assert_equal assert_match 正则表达式问题

Rails minitest assert_equal assert_match regexp question

我需要断言返回的字符串是否包含一个或另一个子字符串。

我是这样写的:

if mail.subject.include?('Pragmatic Store Order Confirmation')
      assert_equal 'Pragmatic Store Order Confirmation', mail.subject
    else
      assert_equal 'There was an error with your payment', mail.subject
    end

但是我想知道如何用 assert_equal 或 assert_match 将它写成一行 我试过了

assert_match( /(Pragmatic Store Order Confirmation) (There was an error with your payment)/, mail.subject )

但我只是想不通它或正则表达式是如何工作的。希望我已经说清楚了。 谢谢!

你已经掌握了基本思路,但正则表达式是错误的。

/(Pragmatic Store Order Confirmation) (There was an error with your payment)/

这将匹配“Pragmatic Store Order Confirmation There was an error with your payment”并捕获“Pragmatic Store Order Confirmation”和“There was an error with your payment”。

如果您想匹配 其他内容,请使用 |.

/(Pragmatic Store Order Confirmation|There was an error with your payment)/

Try it


但是,最好使用 assert_include 进行精确匹配。

subjects = [
  'Pragmatic Store Order Confirmation',
  'There was an error with your payment'
]
assert_include subjects, mail.subject

相当于subjects.include?(mail.subject).


最后,有人应该质疑为什么测试不知道邮件的主题行。这应该取决于生成邮件的原因。您的测试应该类似于...

if payment_error
  assert_equal 'There was an error with your payment', mail.subject
else
  assert_equal 'Pragmatic Store Order Confirmation', mail.subject
end