2013-05-16 54 views
0

我試圖定義工廠爲我的測試是這樣的:嵌套工廠

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

這不是優雅,但我已經在我的工廠遵循了這一模式幾次?

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工廠設置)。