How do I achieve conditional behavior of FactoryGirl based on traits
Asked Answered
K

1

5

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
Kim answered 18/2, 2015 at 13:27 Comment(0)
O
10

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
Orrery answered 18/2, 2015 at 14:24 Comment(2)
I had to wrap the value in {}: unconfirmed { false }Euphonic
Yup - much have changed since 2015!Orrery

© 2022 - 2024 — McMap. All rights reserved.