FactoryBot-创建嵌套对象 [英] FactoryBot - create nested objects
问题描述
我正在学习如何在Rails中进行测试,并且正在为我的问题模型编写工厂:
I'm learning how to test in rails and I'm writing a factory for my question model:
require 'factory_bot'
FactoryBot.define do
factory :question do
sequence(:content) { |n| "question#{n}" }
source "BBC"
year "1999"
end
end
问题是我有一个 has_many:choices
关系,对于这个问题,我应该有5个选择。所以我想知道如何在工厂机器人上做到这一点。请不要从文档中获取该信息,不胜感激。谢谢!
The problem is that I have a has_many :choices
relationship, where I should have 5 choices for my question. So I would like to know how to do that on factory bot. Don't got it from the documentation so would appreciate any help. Thanks!
这是我的问题模型:
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
我的选择模型:
class Choice < ApplicationRecord
belongs_to :question
validates :content, presence: true, allow_blank: false
end
我的工厂代码:
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
我的功能测试(它仍然不执行任何操作,但是由于我的验证,它已经无法创建问题):
And my feature test (it still does nothing, but it already fails just to create the questions because of my validation):
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
推荐答案
可能会发生什么此处使用 select
和 choices
集合代理使Rails尝试从数据库加载集合再次在验证,但尚未持久化。尝试从验证中删除 select
What's possibly going on here is the use of select
with the choices
collection proxy is causing Rails to attempt to load the collection from the DB again during the validation but they haven't been persisted yet. Try removing the select
from your validation
if self.choices.size != 5
select
可能是'确实确实需要,因为 Choice
模型已经验证了内容是否存在。在构建列表时,您可能还需要为问题分配选项
The select
probably isn't really needed anyway since the Choice
model already verifies that content has to be present. You'll probably also need to assign the choices to the question when you build the list
before :create do |question|
question.choices = build_list :choice, 5, question: question
end
这篇关于FactoryBot-创建嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!