开发者

How to test custom messages thrown back by a models validation in Rails

开发者 https://www.devze.com 2022-12-11 05:05 出处:网络
I have this validation in my user model. validates_uniqueness_of :email, :case_sensitive => false, :message => \"Some funky message that ive cleverly written\"

I have this validation in my user model.

validates_uniqueness_of :email, :case_sensitive => false,
              :message => "Some funky message that ive cleverly written"

In my tests I want to ensure that when a user enters a dupe email address that my message definately gets shown but without having to duplicate the error string from above in my test. I dont like that because im sure the message will change as i start thinking about copy. Does rails store these error messages - something which i can call in my tests?

Ive done a general test of

assert @error_messages[:taken] , user.errors.on(:email)

but that would pass on any of the other email related errors ive set validations开发者_如何转开发 up to catch i.e. incorrect formating, blank etc.


I made a quick test, and it looks like the error messages are sorted in the order you wrote your validation statements in your model class (top-down).

That means, you can find the error message for the first validation on an attribute at the first place in the errors array:

user.errors.on(:email)[0]

So, if your user model class contains something like this:

validates_presence_of   :email
validates_uniqueness_of :email, :case_sensitive => false, :message => "Some funky message that ive cleverly written"
validates_length_of     :email

...you'll find your 'funky message' at user.errors.on(:email)[1], but only if at least validates_presence_of triggers an error, too.

Concerning your specific problem: The only way I could think of to not repeat your error message in the test, is to define a constant in your user model and use this instead of directly typing a message for that validation:

EMAIL_UNIQUENESS_ERROR_MESSAGE = "Some funky message that ive cleverly written"
...
validates_uniqueness_of :email, :case_sensitive => false, :message => EMAIL_UNIQUENESS_ERROR_MESSAGE

In your test, you could use this constant, too:

assert_equal User::EMAIL_UNIQUENESS_ERROR_MESSAGE, user.errors.on(:email)[1]


In rspec,

it "should validate uniqueness of email" do
  existing_user = User.create!(:email => email)
  new_user = User.create!(:email => existing_user.email)
  new_user.should_not be_valid
  new_user.errors.on(:email).should include("Some funky message that ive cleverly written")
end
0

精彩评论

暂无评论...
验证码 换一张
取 消