我正在按照这里接受的答案 Factory Girl: How to setup a has_many/through association
我有一个has_many通过关联
class Therapist < ActiveRecord::Base
has_many :clients, dependent: :destroy
has_many :courses, through: :clients
我工厂的女生代码
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
课程工厂
FactoryGirl.define do
factory :course do
client
end
end
当我运行测试时,我收到以下错误
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.
答案 0 :(得分:3)
首先应该创建therapist
工厂,在完成治疗师的创建后,您将附加课程工厂。在您的情况下,factory :therapist_with_course
没有关于therapist
FactoryGirl.define do
factory :therapist do
# The therapist attributes here
after(:create) { |therapist| therapist.courses << FactoryGirl.create(:course) }
end
end