I often get the question from new rubyist "How should I test my model validations in Rails?". A simple example is when we have a `Post` model with two required fields:
# test/models/post_test.rbrequire'test_helper'classPostTest<ActiveSupport::TestCasetest"should not save post without title or body"dopost=Post.newassert_notpost.savepost.title='Test'assert_notpost.savepost.body='Test body'assertpost.saveendend
But this test is already too long and what if you have a lot more required fields? To get around this it is better to test if the validation errors are correct:
# test/models/post_test.rbtest"should have the necessary required validators"dopost=Post.newassert_notpost.valid?assert_equal[:title,:body],post.errors.keysend
Now we cover the existence of the validators with a lot shorter and simpler test.
We can use the same approach to test ther validation rules like `numericality`:
# test/models/post_test.rbtest"should have numeric score"dopost=Post.new(title: 'test',body: 'test body',score: 'test')assert_notpost.valid?assert_equal["is not a number"],post.errors.messages[:score]end
And so on.
As some of the readers pointed out if you need a full blown solution with support of `on` and etcetera thoughbot's [shoulda-matchers](https://github.com/thoughtbot/shoulda-matchers) is has all that.