fespinozacast
fespinozacast

Reputation: 2494

How can I use FactoryBot in db/seeds?

Is it possible to do this?

If so, how can you do it?

Note: FactoryBot was previously named FactoryGirl

Upvotes: 36

Views: 21467

Answers (6)

carot3
carot3

Reputation: 49

In Rails 5.2.6, you can create factories in your db/seeds.rb file. Add include FactoryBot::Syntax::Methods at the top of your seeds.rb file. Below that line, you can create your factories – i.e. user1 = create(:user).

# db/seeds.rb
include FactoryBot::Syntax::Methods

user1 = create(:user)

Upvotes: 3

Michael Greenly
Michael Greenly

Reputation: 311

All you need to do is add require 'factory_bot_rails' to the db/seeds.rb file. This will give you access to your factories.

Note: Gem was previously called FactoryGirlRails

Upvotes: 31

Laurie Young
Laurie Young

Reputation: 138474

(This answer works in rails 3.0.7)

I found the catch is how you set up the Gemfile - you need to do something along the lines of

gem 'factory_girl'

group :test do
  gem 'factory_girl_rails'
end

We found problems having factory_girl_rails outside of the :test environment, which we didn't manage to get to the bottom of (maybe something to do with the way rails does class caching?)

Once that is done, I like to actually load data from a library in lib, something like...

require 'factory_girl'
require 'spec/factories/user_factory'

module Seeds

  class SampleUsers

    def self.run
    u = Factory(:user)
  end
end

And then running this method from within db:seed using

Seeds::SampleUsers.run

Upvotes: 15

Dan Croak
Dan Croak

Reputation: 1669

Josh Clayton, the maintainer of FactoryGirl, recommends against using FactoryGirl in your seeds file. He suggests using plain ActiveRecord instead.

Upvotes: 19

Daniel Pérez Rada
Daniel Pérez Rada

Reputation: 1571

in db/seeds.rb

require 'factory_girl_rails'

10.times do
  FactoryGirl.create :user
end

Upvotes: 14

faber
faber

Reputation: 21

You can insert the following code into your spec_helper.rb, and it make some instances of the data you want (in this case "products" from the yaml file):

seeds_file = File.join(Rails.root, 'db', 'seeds.yml')
config = YAML::load_file(seeds_file)
config["products"].each do |product|
  FactoryGirl.create(:product, product) if !Product.find_by_name(product['name'])    
end

Upvotes: 2

Related Questions