Using factory girl in a Rake task – uninitialized class variable @@configuration in Rails
December 22, 2010 1 Comment
Over the last few days we have been working on a Rails 2.3 app for a client. We wanted to create a rake task that adds a couple of entries to the database (Seeds.rb is obviously better if you are seeding) and thought that we would use factory_girl to help us do this.
When we added factory girl we created something like the following:
require 'factory_girl' require File.dirname(__FILE__) + '/../../spec/factories.rb' namespace :db do desc "do something" task :create => :environment do ... end end
When running this rake task we got the following error which seemed really confusing:
uninitialized class variable @@configuration in Rails /Users/stevesmith/Documents/projects/profinda/.bundle/ruby/1.8/gems/rails-2.3.10/lib/initializer.rb:20:in `configuration' /Users/stevesmith/Documents/projects/profinda/.bundle/ruby/1.8/gems/factory_girl-1.2.4/lib/factory_girl.rb:25
We were loading the environment so what was the problem? Well actually it’s pretty obvious once you know. In the above example we are trying to load factory girl before we actually set up the rails environment which won’t work.
Instead if you do the following everything runs fine:
namespace :db do desc "do something" task :create => :environment do require 'factory_girl' require File.dirname(__FILE__) + '/../../spec/factories.rb' ... end end
This is really obvious if you think about it but it might just save someone a few minutes of debugging!