Using factory_girl within a rake task - getting uninitialized constant
Asked Answered
E

3

6

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.

Egan answered 10/11, 2011 at 17:8 Comment(0)
S
12

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
Sonny answered 10/11, 2011 at 17:14 Comment(1)
Thanks - that has sorted it! As a bonus, do you know where I could put require File.expand_path("spec/factories.rb") so I don't have to include it in every task? Thanks again.Egan
M
1

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
Maros answered 20/8, 2019 at 9:50 Comment(0)
K
0

@dmcnally's answer didn't work for me, as I was getting odd errors of constants not found. Instead, I resolved it by shelling out to rails runner:

sh "rails runner 'FactoryGirl.create :user'"
Kappel answered 19/10, 2015 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.