Joe MooreJoe Moore
DRY, Targeted, and Reusable Testing of ActiveRecord Extensions
edit Posted by Joe Moore on Wednesday March 18, 2009 at 08:39PM

At Pivotal, we are passionate about test driven development, keeping things DRY, and writing readable and understandable code. Satisfying all of these desires can be challenging, especially when writing test code. In particular, ActiveRecord extensions present several challenges: which models using an extension should we test? How do we both test our extension in isolation while also testing all model's usage of that extension? Is it even worth it?

The answer is yes, it is worth it, and it's also fairly easy, readable, understandable, and DRY. I will present both a common problem and a solution, using a cumulation of technologies and techniques from multiple Pivotal projects, in particular using acts_as_fu to create laser-targeted, isolated, and disposable ActiveRecord models for testing extensions and RSpec shared behaviors to minimize the amount of duplicated test code.

Interesting Things

  • Using 'require' explicitly interferes with class reloading in Rails

Frederick Cheung discusses this in more detail here. This might be related to the Selenium + class reloading issues some pivots have experienced in recent weeks. The alternative is to rely on Rails automagic loading or 'require_dependency'.

  • acts_as_fu makes writing database independent tests for models is easier

Props to pivot Pat Nakajima for creating acts_as_fu.