How can I use FactoryBot in db/seeds?
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
Josh Clayton, the maintainer of FactoryGirl, recommends against using FactoryGirl in your seeds file. He suggests using plain ActiveRecord instead.
(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) endend
And then running this method from within db:seed
using
Seeds::SampleUsers.run