user3814030
user3814030

Reputation: 1283

factory girl has_many through association

I am following the accepted answer from here Factory Girl: How to setup a has_many/through association

I have a has_many through association

class Therapist < ActiveRecord::Base

has_many :clients, dependent: :destroy
has_many :courses, through: :clients

On my factory girl code

FactoryGirl.define do
  factory :therapist do
    sequence(:first_name) { |n| "John#{n}" }
    sequence(:last_name)  { |n| "Smith#{n}" }

    factory :therapist_with_course do
      after(:create) { |therapist| therapist.courses <<  FactoryGirl.create(:course) }
     end
   end
 end

The Course factory

FactoryGirl.define do
  factory :course do
    client
  end
end

When I run the test I am getting the following error

Failure/Error: let(:therapist) { create :therapist_with_course }
 ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection:
   Cannot modify association 'Therapist#courses' because the source reflection class 'Course' is associated to 'Client' via :has_many.

Upvotes: 3

Views: 3587

Answers (1)

mr. Holiday
mr. Holiday

Reputation: 1800

First the therapist factory should be created and after the creation of therapist is done you are appending the course factory. In your case you factory :therapist_with_course has no information about the therapist

FactoryGirl.define do
   factory :therapist do
      # The therapist attributes here
      after(:create) { |therapist| therapist.courses << FactoryGirl.create(:course) }
   end
end

Upvotes: 4

Related Questions