我有两个类PublisherLevel和Publisher。如果创建发布者,则PublisherLevel计数应等于14-不同发布者级别类型的计数。在数据库中,我们有一个外键约束。这只是一个查询表。我想做这样的事情:
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岁了,怀疑还有更好的解决方案。规范的做法是什么?
答案 0 :(得分:1)
您似乎想要种子数据。您可以创建自己的种子类以缓存必要的数据:
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
此代码仅是用法的一个示例,您必须对其进行调整以使其根据您的需要运行。