sergserg
sergserg

Reputation: 22264

How to set foreign key ID in factory girl factory?

Here are my models:

class Section < ActiveRecord::Base
  belongs_to :organization
end

class Organization < ActiveRecord::Base
  has_many :sections
end

In my Loan factory, I would like to automatically create an organization and set it for it. How can I accomplish this?

FactoryGirl.define do
  factory :section do
    organization_id???
    title                 { Faker::Lorem.words(4).join(" ").titleize }
    subtitle              { Faker::Lorem.sentence }
    overview              { Faker::Lorem.paragraphs(5).join("\n") }
  end
end

Upvotes: 0

Views: 2194

Answers (1)

gillien
gillien

Reputation: 412

It's possible to set up associations within factories. You need first to have a factory for your organization :

FactoryGirl.define do
  factory :section do
    ...
  end
end

Then you can just call organization, FactoryGirl will take care on generating your organization

FactoryGirl.define do
  factory :section do
    organization
    title                 { Faker::Lorem.words(4).join(" ").titleize }
    subtitle              { Faker::Lorem.sentence }
    overview              { Faker::Lorem.paragraphs(5).join("\n") }
  end
end

if you want to know more you can go here : http://rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md

Upvotes: 2

Related Questions