cod*_*oda 3 rspec ruby-on-rails
json[:errors] = ["Username can't be blank", "Email can't be blank"]
Run Code Online (Sandbox Code Playgroud)
en.yml 中的错误本身提供为:
username: "can't be blank",
email: "can't be blank"
Run Code Online (Sandbox Code Playgroud)
和测试:
expect(json[:errors]).to include t('activerecord.errors.messages.email')
Run Code Online (Sandbox Code Playgroud)
失败是因为它正在查看字符串“电子邮件不能为空”,而“不能为空”与它不匹配。
我的问题是测试子字符串是否包含在数组 json[:errors] 中包含的字符串中的最佳(我的意思是最佳实践)方法是什么
RSpec 提供了一系列匹配器。在这种情况下,您需要使用include
匹配器 ( docs ) 来检查数组的每个元素。而且,您需要使用match
正则表达式匹配器 ( docs ) 来匹配子字符串:
expect(json[:errors]).to include(match(/can't be blank/))
Run Code Online (Sandbox Code Playgroud)
为了便于阅读,match
正则表达式匹配器的别名为a_string_matching
,如下所示:
expect(json[:errors]).to include(a_string_matching(/can't be blank/))
Run Code Online (Sandbox Code Playgroud)
更新:
我刚刚注意到 OP 的问题包括一个具有多个匹配元素的数组。包含匹配器检查数组的任何元素是否与条件匹配。如果要检查数组的所有元素是否符合条件,可以使用 all 匹配器 ( docs )。
expect(json[:errors]).to all(match(/can't be blank/))
Run Code Online (Sandbox Code Playgroud)