我正在尝试测试after_initialize
模型的item
回调(has_many line_items
):
after_initialize :build_default_items, unless: :line_items?
回调:
def build_default_items
LineOfBusiness.all.each do |lob|
line_items.new(line_of_business_id: lob.id)
end
end
我的测试看起来像:
describe 'callbacks' do
let(:user) { create :user }
it 'should build default items' do
lob1 = LineOfBusiness.create(id:1, name: "Name1", eff_date: Date.today,exp_date: Date.tomorrow, create_user: user, update_user: user)
lob2 = LineOfBusiness.create(id:2, name: "Name2", eff_date: Date.today,exp_date: Date.tomorrow, create_user: user, update_user: user)
lob_count = LineOfBusiness.all.count # this is correct as 2
item = build :item
expect(item.line_items.count).to eq(lob_count)
end
end
错误信息如下:
expected: 2
got: 0
(compared using ==)
所以它在回调方法中失败了,它将LineOfBusiness.all
视为Nil
def build_default_items
LineOfBusiness.all.each do |lob| # <-- this is Nil so fails
line_items.new(line_of_business_id: lob.id)
end
end
为什么在回调方法中为什么Nil?
答案 0 :(得分:0)
line_items.count
会向数据库发送查询,并且由于您未在line_items
回调中保存after_initialize
,因此规范将失败。而是尝试使用line_items.size
。
expect(item.line_items.size).to eq(lob_count)