gpt4 book ai didi

activerecord - FactoryGirl 协会 Parent 不能为空

转载 作者:行者123 更新时间:2023-12-04 02:48:31 27 4
gpt4 key购买 nike

我正在尝试使用 FactoryGirl 创建一个测试数据库,该数据库的关联是 Parent has_many Entries。此时抛出Parent不能为空的ActiveRecord验证错误。我在这方面遇到了困难,并且尝试了很多很多方法来创建这个关联的测试数据库。我认为我很接近,但我什至可能不接近并且可能存在基本错误,因此非常感谢任何和所有建议。

我的猜测是散列 { parent_id::id } 没有被传递到 Entry 工厂。那将无法通过验证。但是,我不知道实际情况是这样,即使是这样,我也不知道如何解决。预先感谢您的帮助...

错误是:

ActiveRecord::RecordInvalid: Validation failed: Parent can't be blank

RSpec 调用是:

before(:all) do
rand(11..25).times { FactoryGirl.create(:parent) }
visit "/parents?direction=asc&sort=parent_blog"
end
after(:all) do
Parent.delete_all
end

父模型是:

class Parent < ActiveRecord::Base
has_many :entries, dependent: :destroy
accepts_nested_attributes_for :entries, :allow_destroy => :true
validates :parent_blog, presence: true,
uniqueness: true
end

Entry 模型是:

class Entry < ActiveRecord::Base
belongs_to :parent
validates :entry_blog, presence:true,
uniqueness: true
validates :parent_id, presence: true
end

父工厂是:

FactoryGirl.define do
factory :parent do
sequence(:parent_blog) { |n| "http://www.parent%.3d.com/ss" % n }
entries { rand(5..15).times { FactoryGirl.create(:entry, parent_id: :id) } }
end
end

入口工厂是:

FactoryGirl.define do
factory :entry do
sequence(:entry_blog) { |n| "http://www.parent%.3d.com/ss/entry%.3d" % [n, n] }
parent_id { :parent_id }
end
end

最佳答案

以下对您的工厂定义的修改应该有效。我稍后会回来提供一些解释。

FactoryGirl.define do

factory :parent do
sequence(:parent_blog) { |n| "http://www.parent%.3d.com/ss" % n }
after(:create) {|parent| rand(5..15).times {FactoryGirl.create(:entry, parent: parent)}}
end

factory :entry do
sequence(:entry_blog) { |n| "http://www.parent%.3d.com/ss/entry%.3d" % [n, n] }
parent
end

end

两个变化,在:parent工厂中引入了after的使用和使用parent代替parent_id,都是 RSpec 支持关联的示例,如 https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations 中所述。 .

至于为什么你的代码不起作用,我现在只能提供部分答案。您不能将 entries 作为初始父创建的一部分的原因是在创建父记录之前您没有父 ID,但您需要父 ID 来创建条目,因为Entry 验证 parent_id 的存在。换句话说,当 entries block 在您的父工厂中求值时,parent_id 尚未设置。

我不太清楚的是为什么不能在入口工厂中将parent替换为parent_id并相应的替换parent:parent 在父工厂的 FactoryGirl.create 调用中使用 parent_id: parent.id。我在提交上述内容之前尝试了该变体,但失败了:

  1) test
Failure/Error: rand(11..25).times { FactoryGirl.create(:parent) }
ArgumentError:
Trait not registered: parent_id
# ./spec/factories.rb:4:in `block (4 levels) in <top (required)>'
# ./spec/factories.rb:4:in `times'
# ./spec/factories.rb:4:in `block (3 levels) in <top (required)>'
# ./tmp/factory_spec.rb:5:in `block (3 levels) in <top (required)>'
# ./tmp/factory_spec.rb:5:in `times'
# ./tmp/factory_spec.rb:5:in `block (2 levels) in <top (required)>'

如果我想通了,我会再次更新这个答案。

关于activerecord - FactoryGirl 协会 Parent 不能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292965/

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