如何使用`should validate_presence_of`和自定义错误消息?

Nat*_*ong 26 ruby activerecord rspec shoulda

我正在用Rspec测试我的ActiveRecord模型.我刚刚在我的一个验证中添加了一条自定义错误消息,如下所示:

validates :accepted_terms_at, :presence => {:message => 'You must accept the Terms and Conditions to use this site.'}
Run Code Online (Sandbox Code Playgroud)

现在,以下测试失败:

it { should validate_presence_of(:accepted_terms_at) }
Run Code Online (Sandbox Code Playgroud)

......有错误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方法.

小智 41

它包括在shoulda中的标准:

it { should validate_presence_of(:name).
            with_message(/is not optional/) }
Run Code Online (Sandbox Code Playgroud)

http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/Shoulda/Matchers/ActiveModel:validate_presence_of