Using a 'default' trait in FactoryGirl to avoid unnecessary association creation
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
Just in case someone else is looking for 'default trait' scenario, this was discussed with examples in https://github.com/thoughtbot/factory_bot/issues/528#issuecomment-18289143
Basically, you can define trait with defaults and then use it for different factories. And then you can use appropriate factory with needed configuration.
For example:
FactoryBot.define do
trait :user_defaults do
email { Faker::Internet.unique.email }
username { Faker::Internet.unique.username }
password { "test1234" }
end
factory :with_admin_role, class: User do
user_defaults
after(:create) do |user, _|
user.add_role :admin
end
end
factory :with_readonly_role, class: User do
user_defaults
after(:create) do |user, _|
user.add_role :readonly
end
end
end