在 factory girl / factory bot 中,我如何获得用于第二次查找的条件种子 table

in factory girl / factory bot, how can I have a conditional seed for a second lookup table

我有两个 类 PublisherLevel 和 Publisher。如果我们创建一个发布者,PublisherLevel 计数应该等于 14——不同发布者级别类型的计数。在我们的数据库中,我们有一个外键约束。这只是一个查找 table。我想做这样的事情:

FactoryGirl.define do
  if PublisherLevel.count == 0 
    puts "you have 0 publisher_levels and should seed it"
    seed_publisher_levels
  end
  factory :company do
    name { Faker::Company.name }
    display_name "Sample Company"
    publisher_level 
  end
end

但是第一个 if 语句没有被调用。我看过这个 Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors 但已经 8 岁了,我怀疑有更优雅的解决方案。这样做的规范方法是什么?

您似乎需要种子数据。您可以创建自己的种子 class 来缓存必要的数据:

class Seeds
  def [](name)
    all.fetch(name)
  end

  def register(name, object)
    all[name.to_sym] = object
  end

  def setup
    register :publisher_level_1, FactoryGirl.create(:publisher_level, :some_trait)
    register :publisher_level_2, FactoryGirl.create(:publisher_level, :some_other_trait)
  end

  private

  def all
    @all ||= {}
  end
end

然后在您的 test_helper.rb 中调用:

require 'path/to/seeds.rb'
Seeds.setup

最后,在你的工厂中引用它:

factory :company do
  publisher_level { Seeds[:publisher_level_1] }
end

此代码只是一个用法示例,您必须对其进行调整以使其根据您的需要运行。