我正在用Rspec测试我的ActiveRecord模型。我刚刚在我的一个验证中添加了一条自定义错误消息,如下所示:
validates :accepted_terms_at, :presence => {:message => 'You must accept the Terms and Conditions to use this site.'}
现在,以下测试失败:
it { should validate_presence_of(:accepted_terms_at) }
...错误为Expected errors to include "can't be blank" when accepted_terms_at is set to nil
。
因此测试失败,因为它正在查看验证错误消息并期望找到默认消息。
如何告诉Rspec新的验证消息应该是什么?
1)消息作为参数:
it {should validate_presence_of(:accepted_terms_at, :message => 'your message')}
这会产生错误wrong number of arguments (2 for 1)
2)消息作为链式方法调用
it {should validate_presence_of(:accepted_terms_at).with('your message')}
这会抛出错误,因为没有with
方法。
答案 0 :(得分:40)
它包括在shoulda中的标准:
it { should validate_presence_of(:name).
with_message(/is not optional/) }
答案 1 :(得分:0)
这个测试有效,它不像我想的那样简洁。
it "should validate the presence of accepted_terms_at" do
@user.accepted_terms_at = nil
@user.valid?
message = "You must accept the Terms and Conditions to use this site."
expect {@user.errors.messages.include?(message)}.to be_true
end
答案 2 :(得分:0)
您有两种选择。
首先,你可以忍住在没有接受这些条款时断言该模型无效。
其次,通过定义自定义错误消息来停止测试特定的错误消息:
https://stackoverflow.com/a/7108254/162793
然后,您可以查找错误消息的符号,而不是错误消息的文本。