如何在dbseeds中使用FactoryBot?

问题描述 投票:27回答:5

是否可以这样做?

如果可以,怎么做?

注:FactoryBot以前叫FactoryGirl。

ruby-on-rails factory-bot seed
5个回答
14
投票

(这个答案在rails 3.0.7中有效)

我发现问题的关键在于你如何设置了 Gemfile - 你需要做一些类似于

gem 'factory_girl'

group :test do
  gem 'factory_girl_rails'
end

我们发现问题有 factory_girl_rails 以外 :test 环境中,我们没能弄清楚这个问题(也许和rails做类缓存的方式有关?

一旦完成了这些,我喜欢从lib中的一个库中加载数据,比如......。

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

module Seeds

  class SampleUsers

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

然后从内部运行这个方法 db:seed 使用

Seeds::SampleUsers.run

28
投票

您需要做的就是添加 require 'factory_bot_rails'db/seeds.rb 文件。这将使你可以访问你的工厂。

注:Gem以前叫FactoryGirlRails。


15
投票

乔希-克莱顿,工厂女孩的维护者。建议不要在种子文件中使用FactoryGirl。. 他建议使用普通的ActiveRecord代替。


13
投票

在dbseeds.rb中,你可以在你的spec_helper.rb中插入以下代码。

require 'factory_girl_rails'

10.times do
  FactoryGirl.create :user
end

2
投票

你可以将下面的代码插入到你的spec_helper.rb中,然后它就会生成一些你想要的数据的实例(本例中是yaml文件中的 "产品")。

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
© www.soinside.com 2019 - 2024. All rights reserved.