How to create has_and_belongs_to_many associations in Factory girl

How to create has_and_belongs_to_many associations in Factory girl

Add Comment


  • 2 Answer(s)

    Here is the solution,

    FactoryGirl.define do
     
      factory :company do
       #company attributes
      end
     
      factory :user do
       companies {[FactoryGirl.create(:company)]}
       #user attributes
      end
    end
    

    pecific company you can use factory this way,

    company = FactoryGirl.create(:company, #{company attributes})
    user = FactoryGirl.create(:user, :companies => [company])
    

    Answered on January 11, 2019.
    Add Comment

    Two different factories,

    Factory.define :user, :class => User do |u|
      # Just normal attributes initialization
    end
     
    Factory.define :company, :class => Company do |u|
      # Just normal attributes initialization
    end
    

    Using test-cases,

    Factory(:user, :companies => [Factory(:company)])
    

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.