[英]How to write down the rspec to test rescue block.?
我有這樣的方法
def className
def method_name
some code
rescue
some code and error message
end
end
那么,如何寫下 rspec 來測試救援塊..?
如果你想拯救,這意味着你希望some code
引發某種異常。
您可以使用RSpec 存根來偽造實現並強制出錯。 假設執行塊包含一個可能引發的方法
def method_name
other_method_that_may_raise
rescue => e
"ERROR: #{e.message}"
end
將存根掛鈎到規范中的該方法
it " ... " do
subject.stub(:other_method_that_may_raise) { raise "boom" }
expect { subject.method_name }.to_not raise_error
end
您還可以通過測試結果來檢查救援處理程序
it " ... " do
subject.stub(:other_method_that_may_raise) { raise "boom" }
expect(subject.method_name).to eq("ERROR: boom")
end
不用說,您應該引發一個錯誤,它可能由實際實現而不是一般錯誤引發
{ raise FooError, "boom" }
並只拯救那個Error
,假設這是相關的。
作為旁注,在 Ruby 中你定義一個類:
class ClassName
不
def className
就像你的例子一樣。
你可以存根返回錯誤
例如,你有這樣的方法類:
class Email
def self.send_email
# send email
rescue
'Error sent email'
end
end
所以引發錯誤的 rspec 是
context 'when error occures' do
it 'should return error message' do
allow(Email).to receive(:send_email) { err }
expect(Email.send_email).to eq 'Error sent email brand'
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.