2015-11-12 46 views
1

我有這樣一個方法,該方法的副作用:如何測試這引起了錯誤

def method 
    # .. 
    begin 
    some_invokation 
    rescue StandardError 
    # some_other_stuff 
    raise 
    end 
    # .. 
    User.create! 
end 

現在我可以測試這種方法引發異常:

expect { method }.to raise_error(StandardError) 

而且我會喜歡測試用戶沒有被創建。

expect { method }.not_to change { User.count } 

它不起作用。它表明這個例外被提出。我試圖嘲弄提高調用:

allow_any_instance_of(described_class).to receive(:raise) 

但在這種情況下,我的method不被中斷,並創建用戶。有沒有其他方法可以做到這一點?

回答

2

也許是這樣的:

expect { 
    method rescue nil 
}.not_to change { User.count } 
0

這可能做到這一點:

expect { method }.to raise_error(StandardError) 
expect { method rescue 'method rescued' }.to eq('method rescued') 
expect { method rescue 'method rescued' }.not_to change { User.count }