[英]factory girl and nested_attributes in rails 3
I have 2 models, one which accepts attributes for the other and I'm trying to find a clever way to use Factory girl to setup the data for both. 我有2个模型,一个接受另一个的属性,我试图找到一个聪明的方法来使用Factory girl为两者设置数据。
Class Booking
has_many :booking_items
accepts_nested_attributes_for :booking_items
Class BookingItem
belong_to :booking
Factory.define :booking do |f|
f.bookdate Date.today+15.days
f.association :space
f.nights 2
f.currency "EUR"
f.booking_item_attributes Factory.build(:booking_item) # doesn't work
end
Factory.define :booking_item do |f|
f.association :room
f.bookdate Date.today
f.people 2
f.total_price 20
f.association :booking
end
require "spec_helper"
describe Booking do
before(:each) do
@booking = Factory.create(:booking)
end
it "should be valid" do
#needs children to be valid
@booking.should be_valid
end
end
I looked around the rdocs but couldn't seem to find what I was looking for. 我环顾了rdocs,但似乎无法找到我想要的东西。
If I understood you correctly, you want to do this, but with terser syntax: 如果我理解正确,你想要这样做,但使用更简洁的语法:
booking_item = Factory(:booking_item, :people => 4)
booking = Factory(:booking, :booking_item => booking_item)
Of cause you can shortcut it like this: 因为你可以像这样快捷方式:
def with_assocs factory, assocs_hashes = {}, attrs = {}
assoc_models = Hash[ assocs_hash.map { |k, v| [k, Factory(k, v)] } ]
Factory factory, attrs.merge(assoc_models)
end
And use like this: 并使用这样的:
@booking = with_assocs :booking, :booking_item => {:people => 3}
@booking.should be_valid
In active_factory plugin with similar factory definitions it would look like this: 在具有类似工厂定义的active_factory插件中 ,它看起来像这样:
models { booking - booking_item(:people => 3) }
booking.should be_valid
Unfortunately I haven't yet implemented integration with factory_girl. 不幸的是,我还没有实现与factory_girl的集成。 Though if you interested any input is very welcome.
虽然如果你感兴趣任何意见,非常欢迎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.