Thursday, 3 September 2009

Excuting Rails Unit Tests without blowing away your database

Okay ...

I have my nice shiny rails app. I have written a heap of tests. But I don't want to blow the TEST database away each time I execute rake test:units.

Be aware when you use say "rake test" it calls "rake db:test:prepare" which essentially blows away your test database and reloads it.

There are a couple of approaches:

One: Run the test through Ruby and not Rake
-------------------------------------------
Run your test: ruby -I test test/unit/my_test.rb

The -I flag ensures that the file /test/test_helper.rb is loaded.

You could then write your own rake task to run all the unit tests.

Two: Write your own rake task to use instead of rake test:units
---------------------------------------------------------------
In this approach. The aim is to ensure that the "db:test:prepare" task is not called. You do this by clearing the prerequisites for "rake test:units"

i.e.
task :test_units do
Rake::Task['test:units'].prerequisites.clear
Rake::Task['test:units'].invoke
end

You then invoke your task: "rake test_units"
Also call "rake -T" to see your task listed.

For more details:
Check out Paul Barry's post
Jay Field's post