Testing Rails data migrations using RSpec

I’d like to share an example (Gist) of testing a staged ActiveRecord data migration using RSpec and Factory Girl.

The example here splits Author information out of an existing Post model.

The trouble with a data migration that  moves information is that its models are defined for the “new” schema, but has to operate on data stored in the “old” schema.  I see two alternative approaches:

  1. Use inline models to represent your old schema
  2. Run the migration in stages (1: add new model, copy data, 2: remove old fields)
I tried the second approach first, and that’s what’s implemented in this gist.

Points of interest and gotchas:

  1. Migrations are just more Ruby code.  Require the migration file and test it just like any other code you write.
  2. Factory girl makes it just as easy to seed “old” data as “new”.   Just use Factory.build, and in Rails3, use Model.save(:validations=>false) to skip validation checks.
  3. Use ActiveRecord::Migration.up_without_benchmarks to suppress output from migrations.  I didn’t find any documentation for this method, though up_with_benchmarks shows up in APIDock.

We’ve been thinking about the robustness of ActiveRecord migrations for a few weeks now.  Look for more detailed discussion of migrations in general in a follow on post.

Post a Comment