Simple syntax for testing Validation errors
I'm using Rails 2.0.5, and when I want to assert that a model will fail validation, I check the errors.full_messages
method, and compare it to an array of expected messages.
created = MyModel.new
created.field1 = "Some value"
created.field2 = 123.45
created.save
assert_equal(["Name can't be blank"], created.errors.full_messages)
To assert that validation succeeds, I just compare to an empty array. You can do something very similar to check that a Rails controller has no error messages after a create or update request.
assert_difference('MyModel.count') do
post :create, :my_model => {
:name => 'Some name'
}
end
assert_equal([], assigns(:my_model).errors.full_messages)
assert_redirected_to my_model_path(assigns(:my_model))
You don't mention what testing framework that you're using. Many have macros that make testing activerecord a snap.
Here's the "long way" to do it without using any test helpers:
thing = Thing.new :param1 => "Something", :param2 => 123
assert !thing.valid?
assert_match /blank/, thing.errors.on(:name)