4

我有兩個模型,一個接受另一個屬性,我試圖找到一個聰明的方式來使用Factory Girl來設置兩者的數據。工廠女孩和rails中的嵌套屬性3

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 

booking_spec

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 

我看了看周圍的rdocs但也似乎無法找到什麼,我一直在尋找。

回答

8

如果我理解正確的,你想這樣做,但更簡潔的語法:

booking_item = Factory(:booking_item, :people => 4) 
booking = Factory(:booking, :booking_item => booking_item) 

原因,你可以通過快捷鍵像這樣:

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 

而且使用這樣的:

@booking = with_assocs :booking, :booking_item => {:people => 3} 
@booking.should be_valid 

active_factory plugin與類似的工廠定義它看起來像這樣:

models { booking - booking_item(:people => 3) } 
booking.should be_valid 

不幸的是,我還沒有實現與factory_girl的集成。雖然如果你感興趣的任何投入是非常受歡迎的