This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.
Unit Testing ActiveRecord
In the unit tests we wrote previously, we tested everything in the class. The rule of thumb was that everything needs to be tested. That has not changed now that we are working with ActiveRecord—each method still needs a test.
But what testing should be done on the basic database CRUD (Create, Read, Update, Delete)? After all, that is what is most different about classes that inherit from ActiveRecord, right? It may surprise you to learn that we do not need to test basic CRUD.
Why not? ActiveRecord handles all of our database activity for us. It knows how to connect to the database, how to create, find, read, update, delete, use conditions and sort. That is the reason why we are using a framework like Rails to begin with: because we can inherit all that ActiveRecord goodness without having to rewrite it ourselves. We can trust that ActiveRecord will do its job correctly.
photo by Tomás Castelazo
That is not blind trust—ActiveRecord has its own unit tests that the core Rails team uses to insure that it works properly. Therefore we can assume that everything our class inherits from ActiveRecord is solid and tested. It was unit tested before we installed it. We just need to focus on our code in the subclass.
The corollary to “Test Everything” is: “If it is code you added, it is code you need to test.”
(more…)