如何写下 rspec 来测试救援块.? [英] How to write down the rspec to test rescue block.?

查看:23
本文介绍了如何写下 rspec 来测试救援块.?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的方法

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

那么,如何写下 rspec 来测试救援块..?

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

推荐答案

如果你想拯救,就意味着你希望 some code 引发某种异常.

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

您可以使用 RSpec 存根 伪造实现并强制出错.假设执行块包含一个可能引发的方法

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" }

并仅挽救那个 Error,假设这是相关的.

and rescue only that Error, assuming this is relevant.

作为旁注,在 Ruby 中您定义一个类:

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

class ClassName

不是

def className

就像你的例子一样.

这篇关于如何写下 rspec 来测试救援块.?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆