Taking Rails Tests to the Next Level

Jay Fields, Associate, ThoughtWorks

Date: Friday, May 18
Time: 11:45am - 12:35pm
Location: Oregon Ballroom 204

With regards to testing, developers who are focused on creating a mature test suite have begun deviating from the traditional Rails way. The largest issue with the default Rails test structure is that the unit tests currently run against the database. To resolve this issue it is possible to reclassify your tests into the following categories:

  • unit: classes which test individual behavior of domain logic without hitting the database
  • functional: tests for collaborating classes that may access the database or work in conjunction with various other classes
  • integration: larger grained tests, each touching several pieces of the application

To ensure that unit tests do not call out to the database, it is possible to redefine the ActiveRecord::Base.connection to throw an exception on access. This also has the side effect of removing the dependency on loading fixture data, which increases speed.

After removing the ability to access the database you will need a way to redirect all method calls that did previously. Replacing the database can be accomplished by using mocks and stubs. Currently, the most popular mocking and stubbing frameworks are Mocha and Stubba, respectively. Much of their popularity is based on an API that promotes conciseness, and high readability.

Utilizing mocks and stubs also decouples dependencies. By decoupling the dependencies of your code, classes can be tested in isolation which then reduces the number of cascading failures.

Following the recipe outlined above reduces the number of functional and integration tests that are necessary. This, of course, reduces the overall time to run the tests; therefore, developers are encouraged to run the test suite as frequently as possible.

Conference News and Coverage