How to write down the rspec to test rescue block.?

心已入冬 提交于 2020-06-08 08:12:18

问题


I have method like this

def className  
  def method_name
    some code  
  rescue  
    some code and error message  
  end  
end

So, How to write down the rspec to test rescue block..?


回答1:


If you want to rescue, it means you expect some code to raise some kind of exception.

You can use RSpec stubs to fake the implementation and force an error. Assuming the execution block contains a method that may raise

def method_name
  other_method_that_may_raise
rescue => e
  "ERROR: #{e.message}"
end

hook the stub to that method in your specs

it " ... " do
  subject.stub(:other_method_that_may_raise) { raise "boom" }
  expect { subject.method_name }.to_not raise_error
end

You can also check the rescue handler by testing the result

it " ... " do
  subject.stub(:other_method_that_may_raise) { raise "boom" }
  expect(subject.method_name).to eq("ERROR: boom")
end

Needless to say, you should raise an error that it's likely to be raised by the real implementation instead of a generic error

{ raise FooError, "boom" }

and rescue only that Error, assuming this is relevant.


As a side note, in Ruby you define a class with:

class ClassName

not

def className

as in your example.



来源:https://stackoverflow.com/questions/20999426/how-to-write-down-the-rspec-to-test-rescue-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!