Schema loading for tests in rails

February 04, 2011

I’m reading The Rails 3 Way by Obie Fernandez, and it says

Every time you run tests, Rails dumps the schema of your development database and copies it to the test database using an autogenerated schema.rb script.

In my experience this isn’t quite what happens. From what I’ve observed:

  • schema.rb gets generated when you call rake db:migrate
  • the schema gets loaded from schema.rb to your test database when you call rake db:test:prepare
  • when you run tests, the calls to the database inside each of the tests are run within a transaction that gets rolled back at the end of the test

In practice, you could therefore load seed data into your test database after calling rake db:test:prepare and you wouldn’t lose this every time you run your tests.

namespace :db do
  namespace :test do
    desc "Init bare bones test data"
    task :seed_db do
      # your seed data here
    end
  end
end
Rake::Task["db:test:prepare"].enhance do
  Rake::Task["db:test:seed_db"].invoke
end

Is this a good idea? Well, It depends. I’m working on one project where it is extremely helpful. Perhaps when we’ve gotten things refactored a bit it won’t be necessary anymore.