简体   繁体   English

如何在 db/seeds 中使用 FactoryBot?

[英]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注意:FactoryBot 之前被命名为 FactoryGirl

All you need to do is add require 'factory_bot_rails' to the db/seeds.rb file.您需要做的就是将require 'factory_bot_rails'添加到db/seeds.rb文件中。 This will give you access to your factories.这将使您可以访问您的工厂。

Note: Gem was previously called FactoryGirlRails注意:Gem 以前称为 FactoryGirlRails

Josh Clayton, the maintainer of FactoryGirl, recommends against using FactoryGirl in your seeds file . FactoryGirl 的维护者 Josh Clayton建议不要在你的种子文件中使用 FactoryGirl He suggests using plain ActiveRecord instead.他建议改用普通的 ActiveRecord。

(This answer works in rails 3.0.7) (这个答案适用于 rails 3.0.7)

I found the catch is how you set up the Gemfile - you need to do something along the lines of我发现问题在于你如何设置Gemfile - 你需要按照以下方式做一些事情

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?)我们发现在:test环境之外有factory_girl_rails的问题,我们没有设法深入了解(也许与 rails 进行类缓存的方式有关?)

Once that is done, I like to actually load data from a library in lib, something like...完成后,我喜欢从 lib 中的库实际加载数据,例如...

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然后从db:seed使用

Seeds::SampleUsers.run

in db/seeds.rb在 db/seeds.rb 中

require 'factory_girl_rails'

10.times do
  FactoryGirl.create :user
end

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):您可以将以下代码插入到您的 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

In Rails 5.2.6, you can create factories in your db/seeds.rb file.在 Rails 5.2.6 中,您可以在db/seeds.rb文件中创建工厂。 Add include FactoryBot::Syntax::Methods at the top of your seeds.rb file.seeds.rb文件的顶部添加include FactoryBot::Syntax::Methods Below that line, you can create your factories – ie user1 = create(:user) .在该行下方,您可以创建您的工厂——即user1 = create(:user)

# db/seeds.rb
include FactoryBot::Syntax::Methods

user1 = create(:user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM