我正在使用 rspec 测试我的模型的验证,并期待一条错误消息。但是,消息的确切文本可能会发生变化,所以我想更宽容一点,只检查部分消息。
由于 Spec::Matchers::include 方法只适用于字符串和集合,我目前正在使用这个结构:
@user.errors[:password].any?{|m|m.match(/is too short/)}.should be_true
这可行,但对我来说似乎有点麻烦。是否有更好(即更快或更像 ruby)的方法来检查数组是否包含正则表达式的字符串,或者是否有一个 rspec 匹配器可以做到这一点?
最佳答案
我会推荐做
@user.errors[:password].to_s.should =~ /is too short/
很简单,因为它会在失败时给你一个更有帮助的错误。如果你使用 be_any
那么你会收到这样的消息......
Failure/Error: @user.errors[:password].should be_any{ |m| m =~ /is too short/}
expected any? to return true, got false
但是,如果您使用 to_s
方法,那么您将得到如下内容:
Failure/Error: @user.errors[:password].to_s.should =~ /is too short/
expected: /is to short/
got: "[]" (using =~)
Diff:
@@ -1,2 +1,2 @@
-/is too short/
+"[]"
因此您可以看到失败的原因,而不必深入挖掘以找出失败的原因。
关于ruby-on-rails - RSpec:通过正则表达式匹配字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4146016/