Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use `should validate_presence_of` with a custom error message?

I'm testing my ActiveRecord models with Rspec. I've just added a custom error message to one of my validations, like this:

validates :accepted_terms_at, :presence => {:message => 'You must accept the Terms and Conditions to use this site.'} 

Now the following test fails:

it { should validate_presence_of(:accepted_terms_at) } 

... with the error Expected errors to include "can't be blank" when accepted_terms_at is set to nil.

So the test fails because it's looking through the validation error messages and expects to find the default one.

How can I tell Rspec what the new validation message should be?

What I've tried

1) Message as an argument:

it {should validate_presence_of(:accepted_terms_at, :message => 'your message')}

This gives the error wrong number of arguments (2 for 1)

2) Message as a chained method call

it {should validate_presence_of(:accepted_terms_at).with('your message')}

This throws an error because there is no with method.

like image 990
Nathan Long Avatar asked Dec 08 '11 15:12

Nathan Long


1 Answers

It's included and standard in shoulda :

it { should validate_presence_of(:name).             with_message(/is not optional/) } 

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

like image 175
tal Avatar answered Oct 14 '22 17:10

tal