我有两个相互依赖的模型才有效。我如何为他们创建有效的工厂?

I have two models that depend on each other to be valid. How do I create valid factories for them?

我有一个 Survey 模型和 Question 模型如下。 Survey 必须至少有 1 个 Question,并且 Question 必须属于如下所示的 Survey

class Survey < ActiveRecord::Base
  has_many :questions, class_name: 'Question', inverse_of: :survey

  validates :title, presence: true, length: { maximum: 200 }
  validates_length_of :questions, maximum: 100, minimum: 1
end

class Question < ActiveRecord::Base
  belongs_to :survey, class_name: 'Survey', inverse_of: :questions

  validates :title, presence: true, length: { maximum: 200 }
  validates :survey, presence: true
end

当我编写如下所示的工厂时,我会收到 Whosebug 错误,因为 Survey 将在创建后构建一个 Question,而 Question 将在创建后构建一个 Survey,从而导致无限循环。

FactoryBot.define do
  factory :question, class: Question do
    association :survey, factory: :survey
    title  { Faker::Lorem.characters(10) }

  end
end

FactoryBot.define do
  factory :aya_pg_portfolio_survey_survey, class: Survey do
    after(:build) do |survey|
      survey.questions = build_list(question, 5)
    end

    title { Faker::Lorem.characters(10) }
  end
end

然后我想删除问题工厂中的调查关联或删除调查工厂中的 after(:build) 回调。然而,这将导致无效的工厂。

似乎应该有一个简单的方法来解决这个问题,因为我只有两个简单的模型需要另一个,但我被卡住了...

为什么不让调查工厂指向没有调查工厂的问题工厂呢?

FactoryBot.define do
  factory :question do
    title  { Faker::Lorem.characters(10) }
    survey nil

    factory :question_and_survey do
      survey
    end
  end
end

这确实意味着这个 create(:question_and_survey) 会 return 调查中的一个问题,总共有 6 个问题。总比没有好吧?

但是正如对您的问题的评论,您确实应该考虑允许创建一个空的调查。就是少了很多扯头发。

Reference to inheritance in factorybot