Search code examples
ruby-on-railsdevisecucumberfactory-botmodel-associations

Factory_girl simple association between two models


FactoryGirl.define do

factory :agency do
    name "Example Inc"
    available_items "20"
    recruiter     # recruiter.id
end

factory :recruiter do
    email 'example@example.com'
    password 'please'
    password_confirmation 'please'
    # required if the Devise Confirmable module is used
    # confirmed_at Time.now
end

end

agency.rb

class Agency < ActiveRecord::Base
  belongs_to :recruiter
  validates :name, :presence => true
end

recruiter.rb

class Recruiter < ActiveRecord::Base
    devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

     # Setup accessible (or protected) attributes for your model
     attr_accessible :email, :password, :password_confirmation, :remember_me
     attr_accessible :agency_attributes, :first_name

     has_one :agency, :dependent => :destroy

     accepts_nested_attributes_for :agency
     validates :email, :presence => true
end

authentication_steps.rb

def create_user
  @recruiter = FactoryGirl.create(:recruiter)
end

How can I replicate this Recruiter & Agency association using factory_girl?


Solution

  • I think you should remove recruiter from agency factory and add agency to requiter factory

    FactoryGirl.define do
    
      factory :agency do 
        name "Example Inc"
        available_items "20"
    
        factory :agency_without_recuiter do
          recuiter_id = 1 
        end
    
        factory :agency_with_recuiter do
          recuiter 
        end
      end 
    
      factory :recuiter do
        email 'example@example.com'
        password 'please'
        password_confirmation 'please'
    
        factory :recuiter_with_agency
          agency
        end
      end
    
    end
    

    This should work from both sides

    create(:agency).recuiter => nil
    create(:agency_with_recuiter).recuiter => recuiter
    
    create(:recuiter).agency => nil
    create(:recuiter_with_agency).agency => agency 
    

    Hope it will be usefull. Good luck!