Factory_bot: Is it possible to pass an argument into a trait?

Created on 16 May 2013  路  2Comments  路  Source: thoughtbot/factory_bot

I'm trying to do something like this:

FactoryGirl.create(:referral, :with_sent_referrals => 10)

So the argument 10 would be passed onto the trait :with_sent_referrals.

Is this possible? And if not, could anyone guide me on how to get started monkey patching factorygirl to do it?

Most helpful comment

@chintanparikh You can use ignored attributes plus traits:

factory :post do
  trait :with_comments do
    ignore do
      comments_count 0
    end

    after(:create) do |post, evaluator|
      FactoryGirl.create_list(:comment, evaluator.comments_count, post: post)
    end
  end
end

FactoryGirl.create(:post, :with_comments, comments_count: 3)

All 2 comments

@chintanparikh You can use ignored attributes plus traits:

factory :post do
  trait :with_comments do
    ignore do
      comments_count 0
    end

    after(:create) do |post, evaluator|
      FactoryGirl.create_list(:comment, evaluator.comments_count, post: post)
    end
  end
end

FactoryGirl.create(:post, :with_comments, comments_count: 3)

DEPRECATION WARNING: #ignore is deprecated and will be removed in 5.0. Please use #transient instead.

Was this page helpful?
0 / 5 - 0 ratings