3

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.
Community
  • 1
  • 1
user3814030
  • 1,263
  • 3
  • 20
  • 37
  • How are the associations defined in the `Course` and `Client` models? – zetetic Aug 26 '15 at 18:31
  • class Course < ActiveRecord::Base belongs_to :client class Client < ActiveRecord::Base has_many :courses, dependent: :destroy belongs_to :therapist – user3814030 Aug 27 '15 at 15:49

1 Answers1

4

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
mr. Holiday
  • 1,780
  • 2
  • 19
  • 37