Search code examples
rubytestingfactory-bot

How do I achieve conditional behavior of FactoryGirl based on traits


I have a factory for user. I want the users to be confirmed by default. But given a trait unconfirmed, I don't want them to be confirmed.

While I have a working implementation, which is based on implementation details, rather than on abstraction, I would like to know how to do this properly.

factory :user do
  after(:create) do |user, evaluator|
    # unwanted implementation details here
    unless FactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)
      user.confirm!
    end
  end
  trait :unconfirmed do
  end
end

I'm thinking something along these lines. But this doesn't work and yields an undefined method `unconfirmed'

factory :user do
  ignore do
    unconfirmed = false
  end

  after(:create) do |user, evaluator|
    user.confirm! unless evaluator.unconfirmed
  end

  trait :unconfirmed do
    unconfirmed = true
  end
end

Solution

  • You were almost there:

    factory :user do
      transient do
        unconfirmed { false }
      end
    
      trait :unconfirmed do
        unconfirmed { true }
      end
    
      after(:create) do |user, evaluator|
        user.confirm! unless evaluator.unconfirmed
      end
    end