FactoryBot - 创建嵌套对象

Ron*_*pes 4 rspec ruby-on-rails capybara

我正在学习如何在 Rails 中进行测试,并且正在为我的问题模型编写一个工厂:

require 'factory_bot'

FactoryBot.define do
  factory :question do
    sequence(:content) { |n| "question#{n}" }
    source "BBC"
    year "1999"
  end
end 
Run Code Online (Sandbox Code Playgroud)

问题是我有一段has_many :choices关系,我的问题应该有 5 个选择。所以我想知道如何在工厂机器人上做到这一点。没有从文档中得到它,因此将不胜感激任何帮助。谢谢!

这是我的问题模型:

class Question < ApplicationRecord

  belongs_to :question_status
  belongs_to :user
  has_many :choices

    accepts_nested_attributes_for :choices, limit: 5

  validates :content, :source, :year, presence: true
  validate :check_number_of_choices,


  def check_number_of_choices
    if self.choices.size != 5
        self.errors.add :choices, I18n.t("errors.messages.number_of_choices")
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

我选择的型号:

class Choice < ApplicationRecord

  belongs_to :question

  validates :content, presence: true, allow_blank: false


end
Run Code Online (Sandbox Code Playgroud)

我的工厂代码:

FactoryBot.define do

    factory :question_status do
        name "Pending"
    end

  factory :choice do
    sequence(:content) { |n| "choice #{n}" }
    question
  end


  factory :question do
    sequence(:content) { |n| "question #{n}" }
    source "BBC"
    year "1999"
    user
    question_status

        before :create do |question|
        create_list :choice, 5, question: question
    end

  end

end 
Run Code Online (Sandbox Code Playgroud)

我的功能测试(它仍然什么也不做,但由于我的验证,它已经无法创建问题):

require 'rails_helper'

RSpec.feature "Evaluating Questions" do

    before do
        puts "before"
        @john = FactoryBot.create(:user)
        login_as(@john, :scope => :user)
        @questions = FactoryBot.create_list(:question, 5)
        visit questions_path
    end


    scenario "A user evaluates a question correctly" do
        puts "scenario"
    end


end
Run Code Online (Sandbox Code Playgroud)

Tho*_*ole 5

select这里可能发生的情况是,与集合代理一起使用choices导致 Rails 在验证期间再次尝试从数据库加载集合,但它们尚未被持久化。select尝试从您的验证中删除

if self.choices.size != 5
Run Code Online (Sandbox Code Playgroud)

无论如何,可能select实际上并不需要,因为Choice模型已经验证了内容必须存在。在构建列表时,您可能还需要将选项分配给问题

before :create do |question|
  question.choices = build_list :choice, 5, question: question
end
Run Code Online (Sandbox Code Playgroud)