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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With