Build factories for self referential associations in rails
Asked Answered
T

1

6

I have a typical requirement, I have to address user object as follows

user.referrer and user.referrers.

Basically, user can refer more than one person and one person should be referred by one particular user. So I build associations as follows. They are working great.

class User < ActiveRecord::Base
    attr_accessible :account_number, :display_name, :referrer_id

    has_many :referrers, :class_name => "User", :foreign_key => "referrer_id"
    belongs_to :referrer, :class_name => "User"
end

Now I would like to test assoications in Rspec. I am using factory girl so any one help me to build factories.

I tried as follows but end up with an errors

factory :user do
  gender :male
  name "super test"
  .....
  .....

  factory :referrer do
  end
  association :referrer
end
Transpadane answered 11/3, 2016 at 12:47 Comment(4)
@BilalMaqsood I have updated my question please check it onceTranspadane
Your relationships aren't working. Please have a look at them.Coady
They aren't working. You are using the same key referrer_id for two purposes.Coady
Yes. It is working fine. Relations are working as expected hereTranspadane
D
7

You need to build two factories here, one for user with a referrer and second one for user without a referer - otherwise you'll end up in the infinite creation loop. You might use traits for this:

factory :user do
  gender :male
  name "super test"

  trait :with_referrer do
    association :referrer, factory: :user
  end
end

FactoryGirl.create(:user, :with_referrer)
Didymium answered 14/3, 2016 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.