views:

64

answers:

2

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.

+2  A: 

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]
Daniel Pietzsch
thanks for the reply. Yes i thought about the possiblility of using a constant, just wondered what everyone else did. Thanks for your suggestions!
adam
+2  A: 

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
Selva
thanks selva for the code. Thats pretty much what i`ve got, its the manual typing out my error message that i wanted to solve though.
adam