0
我试图测试这个after_initialize
回调这对item
模型(这HAS_MANY line_items
):Rspec的,工厂的女孩,after_initialize
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
任何想法,为什么它的无回调方法?
如果'LineOfBusiness'为空,则'LineOfBusiness.all'将给予'[]',而非'nil'和'each'循环不应该得到重复。 –
循环没有迭代,但为什么LineOfBusiness是空的?你是正确的,因为该循环没有迭代,但是如果将其更改为'item = create:item',那么LineOfBusiness.all.count应该是2,就像在测试方法 – user3437721
中一样,它有什么区别吗? – Doon