Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 370
branch14 Avatar asked Feb 18 '15 13:02

branch14


1 Answers

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
like image 114
dgilperez Avatar answered Nov 15 '22 07:11

dgilperez