Search code examples
ruby-on-railsfactory-bot

Using a 'default' trait in FactoryGirl to avoid unnecessary association creation


Is it possible to define a default trait in FactoryGirl? If I define a factory like this (where both question_response belongs_to question):

factory :question_response do
  question
  work_history

  trait :open do
    question { FactoryGirl.create :question, question_type: 'open' }
  end
end

When I do FactoryGirl.create :question_response, :open it will first create a default question and then create another inside the trait, which is an unnecessary operation.

Ideally I'd like to do this:

factory :question_response do
  work_history

  trait :default do
    question { FactoryGirl.create :question, question_type: 'yes_no' }
  end

  trait :open do
    question { FactoryGirl.create :question, question_type: 'open' }
  end
end

And then doing FactoryGirl.create :question will use the default trait, but it doesn't seem to be possible.


Solution

  • When I do FactoryGirl.create :question_response, :open it will first create a default question and then create another inside the trait

    It's not true. if you specify the trait with question, it will overwrite the factory behavior before creation so that it does not create a default question.

    I checked it with FactoryGirl v4.5.0