FactoryBot trait

factory_bot/GETTING_STARTED.md at master · thoughtbot/factory_bot

trait 内 trait

factory :order do
  trait :completed do
    completed_at { 3.days.ago }
  end

  trait :refunded do
    completed
    refunded_at { 1.day.ago }
  end
end

trait with transient

factory :invoice do
  trait :with_amount do
    transient do
      amount { 1 }
    end

    after(:create) do |invoice, evaluator|
      create :line_item, invoice: invoice, amount: evaluator.amount
    end
  end
end

trait 内 trait + transient

factory :invoice do
  trait :with_10_amount do
  	amount { 10 }
    with_amount
  end

  trait :with_amount do
    transient do
      amount { 1 }
    end

    after(:create) do |invoice, evaluator|
      create :line_item, invoice: invoice, amount: evaluator.amount
    end
  end
end

発表資料

ちなみにFacotryBotの使い方に関しては過去に発表したことがあるので、ペタリ。