测试 rspec 中的字符串数组中是否存在子字符串

Test that a substring is present in array of strings in rspec

json[:errors] = ["Username can't be blank", "Email can't be blank"]

en.yml 中的错误本身提供为:

username: "can't be blank",
email: "can't be blank"

和测试:

expect(json[:errors]).to include t('activerecord.errors.messages.email')

失败是因为它正在查看字符串 "Email can't be blank",而 "can't be blank" 不匹配它。

我的问题是什么是最好的(我指的是最佳实践)测试方法 该子字符串包含在数组 json[:errors]

中包含的字符串中

RSpec 提供了一系列匹配器。在这种情况下,您需要使用 include 匹配器 (docs) to check each element of the array. And, you'll need to use the match regex matcher (docs) 来匹配子字符串:

expect(json[:errors]).to include(match(/can't be blank/))

为了便于阅读,match 正则表达式匹配器别名为 a_string_matching,如下所示:

expect(json[:errors]).to include(a_string_matching(/can't be blank/))

更新:

我刚刚注意到 OP 的问题包括一个包含多个匹配元素的数组。 include 匹配器检查数组的任何元素是否符合条件。如果要检查数组的所有元素是否符合条件,可以使用所有匹配器 (docs).

expect(json[:errors]).to all(match(/can't be blank/))