Testing Ruby on Rails Models - Validators
In the rails way of life, all of us developers should test our code, but if you take a look on most of the companies around there, that is not totally true.
So what you can do to change that? that is simple, Start creating tests.

Yup, I know this is a stupid thing to tell, but believe me, one day you will be in a big project with no/really small test suite. Be brave :P
New projects
Please, start your project creating tests. Doesn’t matter if you’re using TDD, BDD, XYZ, just do it ;)
Already runnings projects
You came to a new company and the test suite is very small or doesn’t exist, don’t panic. You’re not going to have a easy path, but you’re not going to die.
Here is my advice:
- You’re starting to understanding the project, so every class that you open, create at least the validations tests (presence, unique, inclusion_of…). If anyone remove a validation by a mistake or not, a test will break and you will know that ;)
- The next step is to every method that you’re working on, you create a test before touch the code. I like to create a test that will return the expected and others to cover “unexpected” values.
On my small rails todo project, here are the initial tests.
I have a task.rb and the name and related user are required.
class TaskTest < ActiveSupport::TestCase
task = Task.new
assert task.invalid?
assert task.errors.include?(:name)
assert task.errors.include?(:user)
end
I started a new object and assert that have at least one error on the required attributes.
I don’t care which error is being returned, I only care the attribute is not valid. Test a specific error became much verbose.
To make easy to test and make sure a specific attribute is being validated you could use the gem shoulda matchers. Here is a refactoring using the gem.
class TaskTest < ActiveSupport::TestCase
should validate_presence_of(:name)
should validate_presence_of(:user)
end
Some people will tell: “Why test validations? Are you testing if the rails validator is working?”
For some time I didn’t tested these validator because of that, till one day a validator was removed by mistake and we had a lot of problems u.u
This is why I like to do these tests ;)
Rails have a lot of validators that you can use, so keep studying, coding and testing :)