Using factory girl in a Rake task – uninitialized class variable @@configuration in Rails

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!

Advertisements

About Steve Smith
Software developer (often ruby, rails but I enjoy loads of languages), semantic tech. fanboy, skydiver, all round geek. Owner of dynamic:edge (hire us) the makers of CloudMailin.com

One Response to Using factory girl in a Rake task – uninitialized class variable @@configuration in Rails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: