FactoryGirl:如何将2个特征组合在一起设置相同的关联

时间:2016-01-13 09:18:15

标签: ruby-on-rails rspec factory-bot

以下工厂:

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 个答案:

答案 0 :(得分:1)

如果您使用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