Clearing the test database between unit and functional tests in Rails (factory_girl)

A command line solution to clear (reconstruct) test database:

rake db:test:prepare

Try writing this in your test/test_helper.rb

eval IO.read(File.expand_path(File.dirname(__FILE__) + "/../Rakefile"))
class Test::Unit::TestCase
 ....
 #db:test:prepare won't work, don't know why,
 #as DROP DATABASE won't execute (me on PostgreSQL).
 #even if I write,
 #ActiveRecord::Base.connection.disconnect!
 Rake::Task["db:reset"].invoke
end

It's not a recommended solution. It makes tests slower, but it works.


A rails plugin called "override_rake_task" could be used to override Rake task "test" which is defined inside if Rails gem. This is a very simple task that executes 3 other tasks one after another: test:units, test:functionals and test:integration. You could include the execution of "db:test:purge" task to clear the test DB before executing test:functionals.

Apparently if you are not using this plugin and if you define a task in your rails application with the same name, rake would execute both tasks: the default and yours.