ibpix
ibpix

Reputation: 319

question about Factory Girl syntax for passing an option to a trait

I am taking over a project that has a question / answer section. I am adding a syndication feature and would like to have a relationship where a question has_one: syndicatable_question.

For my factrory, I have an API like sq = FactoryGirl.create(:question, :with_syndication ) for the simple case and would like something like sq = FactoryGirl.create(:question, :with_syndication(syndicatable_location_id: 345)) but this doesn't work. How could I pass an option / argument for a trait? What changes would I need to make to the factory?

My factory currently looks like this:

FactoryGirl.define do
  factory :question, class: Content::Question do
    specialty_id 2
    subject { Faker::Lorem.sentence }
    body { Faker::Lorem.paragraph }
    location_id 24005

    trait :with_syndication do
      after(:create) do |q, options|
        create(:syndicatable_question, question_id: q.id, syndicatable_location_id: q.location_id)
      end
    end
  end
end

Upvotes: 0

Views: 57

Answers (1)

Maksim P
Maksim P

Reputation: 151

You need to add transient block to your trait

FactoryGirl.define do
  factory :question, class: Content::Question do
    specialty_id 2
    subject { Faker::Lorem.sentence }
    body { Faker::Lorem.paragraph }
    location_id 24005

    transient do
      syndicatable_location_id 24005
    end

    trait :with_syndication do
      after(:create) do |q, options|
        create(:syndicatable_question, question_id: q.id, syndicatable_location_id: options.syndicatable_location_id)
      end
    end
  end
end


FactoryGirl.create(:question, :with_syndication, syndicatable_location_id: 345)

Transient Attributes https://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Traits

Upvotes: 1

Related Questions