使用RSpec和Factory Girl,我创建一条记录,在创建时,会在after_create中自动创建关联的“小时”记录。
但我想测试非默认时间,最好是我在工厂女工厂定义的时间。这就是我想要做的事情:
before (:all) do
@business = Factory(:business_one)
# when that business is saved, a set of default hours is automatically saved as well
# how would I now update the hours with fixtures?
# so, ideally something like:
@business.hours[0] << Factory(:day_one)
@business.hours[1] << Factory(:day_two)
...etc...
end
这是否可行,或者我需要以不同的方式处理这个问题吗?
答案 0 :(得分:2)
为什么不创建备用工厂:
Factory.define :business_with_altnernate_hours, :parent => :business_one do
after_create do |business|
business.hours.clear
Factory.create(:day_one, :business => business)
Factory.create(:day_two, :business => business)
end
end
答案 1 :(得分:0)
这是你可以做的:
@business = Factory(:business_one)
# clear associations so it's in a known state
@business.hours.clear
@business.hours << Factory(:day_one)
@business.hours << Factory(:day_two)
它们仍将按照您推送新关联的顺序插入和保存。