2013-06-20 46 views
9

我有簡單的測試案例:期望raise_error因爲它提出了這個錯誤測試失敗

it "is removed when associated board is deleted" do 
    link = FactoryGirl.create(:link) 
    link.board.destroy 
    expect(Link.find(link.id)).to raise_error ActiveRecord::RecordNotFound 
end 

它失敗,輸出:

1) Link is removed when associated board is deleted 
    Failure/Error: expect(Link.find(link.id)).to raise_error ActiveRecord::RecordNotFound 
    ActiveRecord::RecordNotFound: 
    Couldn't find Link with id=1 
    # ./spec/models/link_spec.rb:47:in `block (2 levels) in <top (required)>' 

任何想法,爲什麼?

回答

20

要發現錯誤,您需要將代碼包裝在一個塊中。您的代碼在不期待錯誤的範圍內執行Link.find(link.id)。正確測試:

it "is removed when associated board is deleted" do 
    link = FactoryGirl.create(:link) 
    link.board.destroy 
    expect { Link.find(link.id) }.to raise_error ActiveRecord::RecordNotFound 
end 
相關問題