我有两个彼此依赖的模型是有效的.我如何为他们创建有效的工厂



我具有以下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

当我编写工厂(例如下面(时,我会遇到一个堆叠的错误错误,因为一项调查将在创建之后提出问题,并且问题将在创建后进行调查,从而导致无限循环。

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)将在调查中返回一个问题,其中有6个问题。总比没有好,对吗?

但是,正如您对您的问题所评论的那样,您确实应该考虑允许创建一个空的调查。

少得多。

引用Factorybot中的继承

相关内容

最新更新