Sebastian Sito
Sebastian Sito

Reputation: 163

Testing Rails model validations

There's many examples of testing RoR model validations. Even keeping the test being DRY across multiple models. But isn't it testing Rails which is already tested?

@user = User.make
@user.name = nil

@user.should_not be_valid

Isn't it testing if Rails validations work?

Upvotes: 2

Views: 245

Answers (3)

Wahaj Ali
Wahaj Ali

Reputation: 4103

Think of a method in your program where you have called update_attribute (update_attribute skips validation). Calling that method leaves the object in an invalid state, however the database still gets updated. Using valid?/invalid? can help you catch such cases.

Upvotes: 1

Mori
Mori

Reputation: 27779

Isn't it testing if Rails validations work?

The point is that it tests that your model validates the presence of name. The fact that it also in effect tests that the Rails validation works, that Rspec works, that Ruby works, that your OS works, and that the rules of physics haven't suddenly changed, is beside the point.

Upvotes: 7

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

The point is that you test that your model is using the validation. I agree with you, though, that your example tests the validation itself, and the test is also somewhat ambiguous.

If you are using the shoulda gem, you can simply use should validate_presence_of(:name).

Upvotes: 2

Related Questions