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.
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
Thank you. I’ll try that and report back.
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