benams
benams

Reputation: 4646

FactoryGirl: how to combine together 2 traits setting the same association

The following factory:

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

provides 2 traits. The uninstalled trait includes the successful trait, but the logs association is overridden when I use it. Is it possible to create a trait that will just append new logs to the mixed-in trait. In the case above, I would like to have the uninstall trait with 3 logs - 2 of success and 1 of uninstall

Upvotes: 1

Views: 2242

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176352

You can't, if you use the logs syntax. You need to use a 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

Upvotes: 1

Related Questions