Sunday 25 March 2012

Seeding the Test Database

Edit: this post was edited with new information as it was found. As such it is a mess. There are two solutions to loading the same seed data in test as the other environments: Loading your seeds.rb from factories in the spec, or loading your seeds into the testing environment. I prefer the first option as you get to make your seeds with FactoryGirl and it gets validated and if you are loading your seeds in spec, you need to call the method to load it before(:all) every time.

I was wondering why some of my tests were not passing after a Rake db:test:prepare
Turns out it clears the database, and the only way I have to get it back using the seeds.rb file is with RAILS_ENV="test" Rake db:seed which seems cumbersome and not really railsy at all.

As a bonus, after I run RAILS_ENV="test" Rake db:seed, I then fail a lot of tests. It seems that seeding the test database breaks FactoryGirl's creates.

Is there a way for me to have my seeds and test them?

At the moment I am looking into ways to get seeds.rb to load a FactoryGirl method that I can use to also populate the test database separately. That seems like an easier approach to loading my seeds.rb into FactoryGirl as it causes already passing tests to fail and behave differently in test to development which is obviously bad.

Asking others seemed a good idea:
http://stackoverflow.com/questions/9861075/how-can-i-load-seeds-rb-into-the-test-database-without-breaking-factorygirl

But in the end I managed to weedle out 2 possible answers myself:

1) Loading Seeds from Spec

In Spec/helpers.rb:

def seed_data
require Rails.root.join('db', 'seeds.rb')
end

2) Loading Spec from Seeds

In Seeds.rb


require Rails.root.join('spec', 'helpers.rb')
require 'rubygems'
require 'factory_girl_rails'
seed_data

In Spec/helpers.rb


def seed_data
  Factory.create(:admin)
  #Create all your objects
end

No comments:

Post a Comment