我正在尝试为我的测试定义工厂:
factory :content do
id
name
after(:create) do |content|
create(:title, :title_id => content.id)
end
end
# --------------
factory :title do
title_id
title_name
after(:create) do |title|
create(:some_other_model, :this_id => title.title_id)
end
end`
所以基本上,我想设置让5个表包含我的测试的一些数据,这需要按特定的顺序完成,以便插入的下一个记录可以具有前一个的id。这可以通过上面定义的工厂进行,只需要一个这样的调用:FactoryGirl.create(:content)
因为它在内部进行工厂中定义的调用
现在,假设我想做同样的事情,但为堆栈中更深层的属性设置一个特定值(例如:some_other_model.name => 'Name')
,我该怎么做?
答案 0 :(得分:0)
这不优雅,但我在工厂里多次遵循这种模式:
factory :foobar do
ignore do
goobar_color nil
end
after(:create) do |foobar, evaluator|
create(:goobar, :foobar => foobar, :goobar_color => evaluator.goobar_color)
end
end
然后,当您创建foobar时,您可以指定相关goobar的颜色:
create(:foobar, :goobar_color => "red")
如果你愿意,你应该能够更深入地扩展它(即让goobar工厂创建一个hoobar对象,其属性可以由foobar工厂设置)。