markstewie
markstewie

Reputation: 9587

How to create belongs_to relationship in Factory girl sequence

I have a Quiz model that belongs_to an Icon, an Icon has_many Quizzes.

In factory girl to create quizzes I had a sequence.

factory :quiz do
  sequence(:title) { |n| "Quiz #{n} Title" }
  sequence(:description) { Faker::Lorem.paragraph(sentence_count = 3) }
end

Since adding the Icon relationship all my tests fail as there is no quiz_id being generated in the factory.

I also have a sequence for icons

  factory :icon do
    sequence(:title) { |n| "Icon #{n}" }
    sequence(:image) { fixture_file_upload(Rails.root + 'spec/fixtures/images/love.png', 'image/png') }
  end

How do I add an icon_id to my quiz factory correctly?

Upvotes: 0

Views: 465

Answers (2)

markstewie
markstewie

Reputation: 9587

I worked it out... if anyone has the same problem. Adding the following to the quiz factory did the job. Obvious in the end!

sequence(:icon) { FactoryGirl.create(:icon) }

Upvotes: 0

Unixmonkey
Unixmonkey

Reputation: 18784

factory :quiz do
  icon # or association(:icon) will also work
  sequence(:title) { |n| "Quiz #{n} Title" }
  sequence(:description) { Faker::Lorem.paragraph(sentence_count = 3) }
end

Upvotes: 1

Related Questions