gpt4 book ai didi

ruby-on-rails - 工厂女郎 : RecordInvalid with association length minimum validation on create

转载 作者:行者123 更新时间:2023-11-28 20:28:17 26 4
gpt4 key购买 nike

我有模型 Questionhas_many Answer。我需要一个问题至少有一个答案,我正在使用 rspec

进行测试
validates :answers, length: { minimum: 1 }

我的工厂:

FactoryGirl.define do
factory :question do
text "Enunciado de la pregunta"
transient do
answers_count 2
end

after(:create) do |q, ev|
create_list(:answer, ev.answers_count, question: q)
end
end

factory :answer do
text "Enunciado de la respuesta"
end
end

但是当我在规范文件中执行 create(:question) 时,它会抛出一个 RecordInvalid 异常(create 会尝试保存模型,但关联的答案是在 create 之后创建的) .

尝试更改为 after(:build) 但效果不佳。

如何在没有回调的情况下构建保留 transient answers_count 参数的所需答案?

最佳答案

如您所知,您需要在保存问题之前创建关联。

我想你可能想做这样的事情:

FactoryGirl.define do
factory :question do
...
answers { [association(:answer, answers_count: 2 )] }
end
end

或者 build_list 方法可能会有所帮助:

after(:build) do |q, ev|
build_list(:answer, ev.answers_count, question: q)
end

我能够使用 after(:build) 让它工作。参见 docs after(:build) 及其回调顺序。

我用这个设置让它在 mongo 中工作:

#spec/models/question_spec.rb
describe Question do
let!( :question ){create :question}

it 'should work', :focus do
expect( question ).to be_valid
puts question.inspect
puts question.answers.inspect
end
end

#spec/factories/questions.rb
FactoryGirl.define do
factory :question do
text "Enunciado de la pregunta"
transient do
answers_count 2
end

after(:build) do |q, ev|
create_list(:answer, ev.answers_count, question: q)
end
end

factory :answer do
text "Enunciado de la respuesta"
end
end

#models/question.rb
class Question
include Mongoid::Document
include Mongoid::Attributes::Dynamic

field :text, type:String

has_many :answers
validates_presence_of :answers
end

#models/answer.rb
class Answer
include Mongoid::Document
include Mongoid::Attributes::Dynamic

field :text, type:String

belongs_to :question
end

我的测试结果是这样的:

Run options: include {:focus=>true}
#<Question _id: 590a20ef8a681843088580bb, text: "Enunciado de la pregunta">
[#<Answer _id: 590a20ef8a681843088580ba, text: "Enunciado de la respuesta", question_id: BSON::ObjectId('590a20ef8a681843088580bb')>, #<Answer _id: 590a20ef8a681843088580bc, text: "Enunciado de la respuesta", question_id: BSON::ObjectId('590a20ef8a681843088580bb')>]
.

Finished in 0.16217 seconds (files took 2.87 seconds to load)
1 example, 0 failures

关于ruby-on-rails - 工厂女郎 : RecordInvalid with association length minimum validation on create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43757284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com