'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



Solution 1:[1]

(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

Solution 2:[2]

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

Solution 3:[3]

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

Solution 4:[4]

in db/seeds.rb

require 'factory_girl_rails'

10.times do
  FactoryGirl.create :user
end

Solution 5:[5]

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

Solution 6:[6]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GabLeRoux
Solution 2 notapatch
Solution 3 Dan Croak
Solution 4 Daniel Pérez Rada
Solution 5
Solution 6 notapatch