Forum: Ruby on Rails Functional test a "create" action when a validation fails

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
kendall (Guest)
on 2006-12-31 01:40
(Received via mailing list)
I'm trying to write a functional test of a "create" action in one of my
controllers.  In the corresponding model I have a
"validates_uniqueness_of :location".  In the test case I am
constructing I have the create fail with the error "Location has
already been taken".  Is there a way I can write an assertion like:
assert_equal "Location has already been taken", [the_actual_error].  I
can't figure out how to retrieve the validation errors.  Thanks.
Jakob S. (Guest)
on 2006-12-31 14:28
(Received via mailing list)
kendall wrote:
>
> I'm trying to write a functional test of a "create" action in one of my
> controllers.  In the corresponding model I have a
> "validates_uniqueness_of :location".  In the test case I am
> constructing I have the create fail with the error "Location has
> already been taken".  Is there a way I can write an assertion like:
> assert_equal "Location has already been taken", [the_actual_error].  I
> can't figure out how to retrieve the validation errors.  Thanks.

assert_equal "has already been taken",
assigns(:your_model_instance).errors(:location)

If my memory fails me and the above doesn't work, check the API
reference for ActiveRecord::Errors for the proper methods.

--
Jakob S. - http://mentalized.net
kendall (Guest)
on 2006-12-31 15:34
(Received via mailing list)
Thank you.  I'll try that and report back.
kendall (Guest)
on 2007-01-01 19:29
(Received via mailing list)
Thanks, Jakob, that was good advice.  I looked at the
ActiveRecord::Errors API and saw that it provides a ".on" method that
returns the error message text when provided with the attribute, which
in this case I assume would be "location_id".

Here is some code that works:

assert_equal 'has already been taken',
       assigns(:my_model_instance).errors.on('location_id')

This next one also works.  Not sure which is better, but I think I'll
keep the latter one for now.

assert_equal ActiveRecord::Errors.default_error_messages[:taken],
     assigns(:my_model_instance).errors.on('location_id')


Appreciate your help,
Kendall
This topic is locked and can not be replied to.