【问题标题】:factory girl has_many through association工厂女孩 has_many 通过协会
【发布时间】:2015-08-26 20:41:03
【问题描述】:

我正在关注此处接受的答案 Factory Girl: How to setup a has_many/through association

我有一个 has_many through 关联

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.

【问题讨论】:

  • Course 和 Client 模型中的关联是如何定义的?
  • 类 Course

标签: rspec factory-bot


【解决方案1】:

首先应该创建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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多