2016-01-13 36 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 
相关问题