Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.2rake-test

How to prevent "rake test" from deleting "rake db:seed" data?


My Ruby version is ruby 1.9.3p385 . My Rails version is 3.2.12.

I use the following to load the test database:

rake db:seed RAILS_ENV=test

Everything works great. All the Factory Girl stuff is loaded nicely.

Contents of test/factories.rb contains the factories. The contents of db/seeds.rb is simply:

FactoryGirl.create(:music_categorization)
FactoryGirl.create(:dance_categorization)

Now, when I run the tests using the following command:

rake test

Rails deletes all the seed data and the tests fail. I'd like a way to prevent "rake test" from deleting data.

The other route I went was to load the seed data as part of the "rake test" command as mentioned in this question. However, what that ends up doing is loading the test data twice (basically db/seeds.rb is called twice for some reason). I abandoned that route and now simply want to do the following to run my tests:

rake db:seed RAILS_ENV=test
rake test

Any help is appreciated. I basically want to prevent rake test from deleting my data OR figure out a way to not have db/seeds.rb called twice.


Solution

  • AFAIK its not usual to use db:seed to load data for your tests, its normally just used to load seed data for development purposes only.

    Instead you should create test data in the actual test file. Usually test data is deleted after each test using something like database_cleaner, so each test starts with an empty database.

    For example in rspec you can load test data in a let block, before block or in the test itself, e.g

    require 'spec_helper'
    
    describe Page do
      let(:user) { FactoryGirl.create(:user) }
    
       before do
         # create some data
       end
    
      it '#name returns XYZ' do
        page = FactoryGirl.create(:page, :user => user)
        page.description.should == 'XYZ'
      end
    
      it '#description returns ABC' do
        page = FactoryGirl.create(:page, :user => user)
        page.description.should == 'ABC'
      end
    end