2016-01-13 22 views
0

下面的工廠:FactoryGirl:如何結合在一起2個特質設置相同的關聯

FactoryGirl.define do  
    factory :program do 
    trait :successful do 
     status :success 
     logs { build_list :program_log, 2, :success } 
    end 

    trait :uninstalled do 
     successful 
     logs { build_list :program_log, 1, :uninstall } 
    end 
    end 
end 

提供2個特點。 uninstalled特徵包括successful特徵,但當我使用它時,logs關聯會被覆蓋。是否有可能創建一個只會將新日誌附加到混入特徵的特徵。在上面的情況下,我想擁有3個日誌的uninstall特徵 - 2個成功和1個卸載

+1

你看過'after(:build)'語法嗎?看起來你可以'後(:build)'做一些像'logs << build_list:whatever_log,1:inst'?有一個很好的例子說明它如何在這裏使用...... http://cookieshq.co.uk/posts/useful-factory-girl-methods/ –

回答

0

如果使用logs語法,則不能。你需要使用callback

FactoryGirl.define do  
    factory :program do 
    trait :successful do 
     status :success 
     after(:build) do |object| 
     object.logs.concat build_list(:program_log, 2, :success) 
     end 
    end 

    trait :uninstalled do 
     successful 
     after(:build) do |object| 
     object.logs.concat build_list(:program_log, 1, : uninstall) 
     end 
    end 
    end 
end 
相關問題