2015-11-16 112 views
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.allNil

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 

任何想法,爲什麼它的無回調方法?

+0

如果'LineOfBusiness'爲空,則'LineOfBusiness.all'將給予'[]',而非'nil'和'each'循環不應該得到重複。 –

+0

循環沒有迭代,但爲什麼LineOfBusiness是空的?你是正確的,因爲該循環沒有迭代,但是如果將其更改爲'item = create:item',那麼LineOfBusiness.all.count應該是2,就像在測試方法 – user3437721

+0

中一樣,它有什麼區別嗎? – Doon

回答

0

line_items.count將觸發查詢到數據庫,並且因爲您不保存line_itemsafter_initialize回調,spec將失敗。請嘗試使用line_items.size

expect(item.line_items.size).to eq(lob_count)