Ruby on rails Factorygirl创建复杂集合
我有一个项目和类别。我想有多个项目,每个有多个类别。我不希望每个项目都有不同的类别,而是与一组共同的类别相关联 有没有办法通过FactoryGirl dsl实现这一点 下面是我如何使用帮助器模块完成的:Ruby on rails Factorygirl创建复杂集合,ruby-on-rails,factory-bot,Ruby On Rails,Factory Bot,我有一个项目和类别。我想有多个项目,每个有多个类别。我不希望每个项目都有不同的类别,而是与一组共同的类别相关联 有没有办法通过FactoryGirl dsl实现这一点 下面是我如何使用帮助器模块完成的: module Features module ItemsHelpers def create_items_with_categories parents = create_list :category, 2 children = [] 5.time
module Features
module ItemsHelpers
def create_items_with_categories
parents = create_list :category, 2
children = []
5.times do
children << (create :category, parent: parents.sample)
end
10.times do
item = build :item
item.categories << children.sample(3)
item.save
end
end
end
end
模块功能
模块项目搁置器
def创建带有类别的项目
父项=创建列表:类别,2
儿童=[]
5.5倍
children通过查看代码,我假设,条目有许多类别:
sequence :name do |n|
"Item - #{n}"
end
factory :item do
name { generate(:name) }
# other fields here..
ignore do # in the latest version, it is: "transient do.."
categories_count 5
end
after(:create) do |item, evaluator|
categories { FactoryGirl.create_list(:category, evaluator.categories_count) }
end
end
您可以将其用作:
let(:categories) { create_list(:category, 10) }
let(:items) { create_list(:item, 5, categories: categories) }
更新:在许多情况下,当您的规格增加时,您不必在创建项目时添加额外的:类别
,因为它将由默认值创建,除非指定。因此,为了保持优雅,请忽略/暂时
因此,您可以:
let(:items) { create_list(:items, 10, categories_count: 3) } # when you need just 3 categories per item!!
最后,它归结为您遵循的首选项和编码结构。我更喜欢两者都有,这样我就不必在创建项目
或项目
工厂时费心添加类别
列表。我不确定是否遵循了代码。为什么不做你在“你可以使用它作为”一节中提供的东西而不做其他的东西呢?您只需创建一个类别列表,然后在创建项目列表时将它们与每个项目关联。所以在这种情况下,每个项目都有相同的类别。那么,为什么瞬态/忽略和事后创建回调在工厂中进行?但是每个项目会为自己生成不同的类别,还是每个项目将使用相同的3个类别?在第一种情况下,相同的类别将被重用/相同,在后一种情况下,将为每个项目生成新的类别。