In my unit tests for my User model, I’m testing some validation cases.
What is really strange, and driving me crazy, is that in the unit
tests, it seems like the save method is causing my validations to
execute twice, and produce duplicate error messages. This is making my
tests fail (because I’m checking for the number of errors that I
expect). In the web browser, only one error message is displayed.
Anyone know what the cause of this could be?
The Model:
validates_length_of :zip_code, :is => 5, :allow_nil => true
The Unit Test:
def test_create_user_with_invalid_zip_code
@u = User.new(
:password => ‘asecurepassword’,
:password_confirmation => ‘asecurepassword’,
:display_name => ‘invalid zip’,
:email => ‘[email protected]’,
:zip_code => ‘265’
)
@u.new_password = true
assert [email protected]
assert_equal 1, @u.errors.count
assert_equal “is the wrong length (should be 5 characters)”,
u.errors.on(:zip_code)
end
the test result:
- Failure:
test_create_user_with_invalid_zip_code(UserTest)
[test/unit/user_test.rb:112]:
<1> expected but was
<2>.
further inspection of the @u instance:
=> #<User:0x38e0598 @password=“asecurepassword”,
@attributes={“salt”=>"", “delete_after”=>nil, “updated_at”=>nil,
“security_token”=>nil, “role”=>nil, “country”=
nil, “zip_code”=>“265”, “gender”=>nil, “token_expiry”=>nil, “is_verified”=>0, “birthday”=>nil, “is_deleted”=>0, “display_name”=>“invalid zip”, “logged_in_at”=>nil, “salted_password”=>"", “created_at”=>nil, “email”=>“[email protected]”}, @password_confirmation=“asecurepassword”, @new_password=false, @errors=#<ActiveRecord::Errors:0x38b7768 @base=#<User:0x38e0598 …>, @errors={“zip_code”=>[“is the wrong length (should be 5 characters)”, “is the wrong length (should be 5 characters)”]}>, @new_record=true>
please help! this is driving me nuts