2011-08-11 94 views
1

我寫了一個rspec測試,它增加了我的一些單位的rubric。工廠女孩協會

我有兩個模型=>專業和單位。 Rubrics有很多單位。 它看起來像這樣:

@rubric.units.push Factory :text_unit 
@rubric.save 

後來我發現factory_girl並試圖重寫 此代碼作爲工廠。但它不起作用。

我該如何在Factory Girl中寫這個關聯。 我嘗試這樣做:

factory :common_rubric , :class => :common_info_rubric do |f| 
    f.sequence(:name) {|n| "common_info_rubric#{n}"} 
    end 

    factory :text_unit, :class => text_info_unit do |f| 
    f.association :common_rubric_with_unit 
    f.sequence(:name) {|n| "text_unit#n}" } 
    end 

    factory :common_rubric_with_unit , :parent => :common_rubric do |f| 
    f.units { |unit| unit.association(:text_info_unit) } 
    end 

我總是有錯誤

SystemStackError: 
     stack level too deep 
+0

問題更新 – nub

+0

所有的問題在模型表的undefault名稱。 並在閱讀後 http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl 我解決了這個問題。它在這裏http://pastie.org/2355251(因爲我不能回答我的問題,直到7小時左右) – nub

回答

1

所有的問題在模型表的undefault名稱。 而讀 http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl 後,我解決問題

factory :common_rubric , :class => :common_info_rubric do |f| 
    f.sequence(:name) {|n| "common_info_rubric#{n}"} 
    end 

    factory :text_unit, :class => :text_info_unit do |f| 
    f.sequence(:name) {|n| "text_unit#{n}" } 
    end 

    factory :common_rubric_with_unit, :parent => :common_rubric do |f| 
    f.after_create {|a| Factory(:text_unit, :rubric => a) } 
    end 
6

你有一個循環引用那裏。當您創建一個text_unit時,它會創建一個關聯的common_rubric_with_unitcommon_rubric_with_unit的定義創建了一個關聯的text_unit,我們又回到了起點。

您需要刪除從兩側的協會之一,這應該工作:

factory :text_unit, :class => text_info_unit do |f| 
    f.association :common_rubric_with_unit 
    f.sequence(:name) {|n| "text_unit#n}" } 
end 

factory :common_rubric_with_unit , :parent => :common_rubric do |f| 
end