Factory Girl - 创建关联记录
Factory Girl - creating associated records
我已尽我最大努力关注本网站上的文档和类似问题,但并不高兴。我正在尝试创建一个有很多邀请的仪式:
ceremony.rb
class Ceremony < ApplicationRecord
has_many :invites, dependent: :destroy
end
invite.rb
class Invite < ApplicationRecord
belongs_to :ceremony
end
在我的规范中,我正在尝试创建与仪式相关的邀请,如下所示:
let(:ceremony) { FactoryGirl.create(:ceremony) }
let(:nom_1) { FactoryGirl.create(:nominee, award: award) }
let(:inv_1) { FactoryGirl.create(:invite, email: nom_1.email, ceremony: ceremony) }
let(:inv_2) { FactoryGirl.create(:invite, ceremony: ceremony) }
let(:inv_3) { FactoryGirl.create(:invite, ceremony: ceremony) }
before do
User.delete_all
end
it 'should return invites not assigned a nominee' do
binding.pry
expect(award.available_nominees).to include(inv_2, inv_3)
end
当测试达到 binding.pry 并且我开始探索时,我可以看到已经创建了一个新仪式,以及 3 个具有该仪式 ID 的新邀请。当我打电话给
ceremony.invites
我收到一个空的关系。当我打电话给
Invite.where(ceremony: ceremony.id)
我收到 [inv_1、inv_2、inv_3]。当我打电话给
inv_1.ceremony
我又领礼了
ceremony.invites
returns 一个空关系。我不知道为什么邀请是用正确的仪式 ID 创建的,但仪式显然没有邀请。非常感谢任何帮助。
在创建 ceremony
时,数据库中没有 invites
。因为 Rails 缓存数据库查询,所以 invites
数组将保持为空,除非:
- 您手动添加邀请:
ceremony.invites = [inv_1, ...]
,
- 您在创建
ceremony
(在工厂或调用工厂时)或 时添加邀请权
- 您重新加载
ceremony
或其 invites
关系。
我会选择第二个选项,并在调用期望值之前添加 ceremony.reload
或 ceremony.invites(true)
。
我已尽我最大努力关注本网站上的文档和类似问题,但并不高兴。我正在尝试创建一个有很多邀请的仪式:
ceremony.rb
class Ceremony < ApplicationRecord
has_many :invites, dependent: :destroy
end
invite.rb
class Invite < ApplicationRecord
belongs_to :ceremony
end
在我的规范中,我正在尝试创建与仪式相关的邀请,如下所示:
let(:ceremony) { FactoryGirl.create(:ceremony) }
let(:nom_1) { FactoryGirl.create(:nominee, award: award) }
let(:inv_1) { FactoryGirl.create(:invite, email: nom_1.email, ceremony: ceremony) }
let(:inv_2) { FactoryGirl.create(:invite, ceremony: ceremony) }
let(:inv_3) { FactoryGirl.create(:invite, ceremony: ceremony) }
before do
User.delete_all
end
it 'should return invites not assigned a nominee' do
binding.pry
expect(award.available_nominees).to include(inv_2, inv_3)
end
当测试达到 binding.pry 并且我开始探索时,我可以看到已经创建了一个新仪式,以及 3 个具有该仪式 ID 的新邀请。当我打电话给
ceremony.invites
我收到一个空的关系。当我打电话给
Invite.where(ceremony: ceremony.id)
我收到 [inv_1、inv_2、inv_3]。当我打电话给
inv_1.ceremony
我又领礼了
ceremony.invites
returns 一个空关系。我不知道为什么邀请是用正确的仪式 ID 创建的,但仪式显然没有邀请。非常感谢任何帮助。
在创建 ceremony
时,数据库中没有 invites
。因为 Rails 缓存数据库查询,所以 invites
数组将保持为空,除非:
- 您手动添加邀请:
ceremony.invites = [inv_1, ...]
, - 您在创建
ceremony
(在工厂或调用工厂时)或 时添加邀请权
- 您重新加载
ceremony
或其invites
关系。
我会选择第二个选项,并在调用期望值之前添加 ceremony.reload
或 ceremony.invites(true)
。