开发者

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


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)
  end
end

And then running this method from within db:seed using

Seeds::SampleUsers.run


in db/seeds.rb

require 'factory_girl_rails'

10.times do
  FactoryGirl.create :user
end


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)


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜