Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using factory_girl within a rake task - getting uninitialized constant

I'm trying to use Factory Girl in a rake task like this:

require 'factory_girl'
require File.expand_path("spec/factories.rb")

namespace :users do

  desc "Create sample users for use in development" 
  task :create_sample_users => :environment do
    Factory(:user, :email => "[email protected]")
    Factory(:approved_user, :email => "[email protected]") 
  end

end

However when I run rake users:create_sample_users I get the error uninitialized constant Entry (Entry is the name of one of my app's classes).

Can anyone tell me how to get Factory girl to see my classes? It's working fine in my tests, just failing in my rake tasks.

like image 981
Mike Avatar asked Nov 10 '11 17:11

Mike


2 Answers

I'm guessing that Rails hasn't loaded your models at the point you are requiring the factories. Try this:

require 'factory_girl'

namespace :users do

  desc "Create sample users for use in development" 
  task :create_sample_users => :environment do
    require File.expand_path("spec/factories.rb")
    Factory(:user, :email => "[email protected]")
    Factory(:approved_user, :email => "[email protected]") 
  end

end
like image 167
dmcnally Avatar answered Nov 15 '22 01:11

dmcnally


For factory_bot which has replaced factory_girl use:

require 'factory_bot'

namespace :users do

  desc "Create sample users for use in development" 
  task :create_sample_users => :environment do
    include FactoryBot::Syntax::Methods

    create(:user, :email => "[email protected]")
  end
end
like image 42
dominik Avatar answered Nov 15 '22 01:11

dominik