Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Recently I switched from fixtures to factory_girl to test my Ruby on Rails application. If I run rake test:units, to run the tests in my /units directory, they all run perfectly. The same is true if I run my functional tests (in my /functional directory) with rake test:functionals.

However, if I simply run rake test, to run both my unit and functional tests together, my validation fails on the second group of tests (functional, in this case), with the message "Validation failed: Name has already been taken."

I believe this is caused by the functional tests creating objects with the same parameters as the objects that were created in the unit tests -- leading me to believe that the test database isn't cleared in between the unit and functional tests.

I use factory_girl's sequencing to have unique attributes for objects, which means that factory_girl is being reset between tests, while the database is not. What can I do to solve this problem? Is there a way to clear the database between my two test packages?

like image 838
NolanDC Avatar asked Jul 27 '09 16:07

NolanDC


2 Answers

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

rake db:test:prepare
like image 176
Amir Samakar Avatar answered Oct 13 '22 18:10

Amir Samakar


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.

like image 23
Vikrant Chaudhary Avatar answered Oct 13 '22 20:10

Vikrant Chaudhary