Search code examples
ruby-on-railsfactory-botseed

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

  • (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