How to achieve FactoryGirl conditional behavior based on traits

I have a factory for the user. I want users to be verified by default. But, given the unconfirmed , I do not want them to be confirmed.

Although I have a working implementation based on implementation details, not 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 think about this. But this does not work and gives an undefined `unconfirmed 'method

 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 
+5
source share
1 answer

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 
+7
source

Source: https://habr.com/ru/post/1213616/


All Articles