Ruby-on-rails 如何在 Rails/RSpec 中测试异常引发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22141601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:25:03  来源:igfitidea点击:

How to test exception raising in Rails/RSpec?

ruby-on-railsrubyrspec

提问by malcoauri

There is the following code:

有以下代码:

def index
    @car_types = car_brand.car_types
end

def car_brand
    CarBrand.find(params[:car_brand_id])
    rescue ActiveRecord::RecordNotFound
        raise Errors::CarBrandNotFound.new 
end

I want to test it through RSpec. My code is:

我想通过 RSpec 测试它。我的代码是:

it 'raises CarBrandNotFound exception' do
    get :index, car_brand_id: 0
    expect(response).to raise_error(Errors::CarBrandNotFound)
end

CarBrand with id equaling 0 doesn't exist, therefore my controller code raises Errors::CarBrandNotFound, but my test code tells me that nothing was raised. How can I fix it? What do I wrong?

id 等于 0 的 CarBrand 不存在,因此我的控制器代码引发 Errors::CarBrandNotFound,但我的测试代码告诉我没有引发任何问题。我该如何解决?我怎么了?

回答by Jakob S

In order to spec error handling, your expectations need to be set on a block; evaluating an object cannot raise an error.

为了规范错误处理,您需要在块上设置您的期望;评估对象不会引发错误。

So you want to do something like this:

所以你想做这样的事情:

expect {
  get :index, car_brand_id: 0
}.to raise_error(Errors::CarBrandNotFound)

See Expect errorfor details.

有关详细信息,请参阅预期错误

I am a bit surprised that you don't get any exception bubbling up to your spec results, though.

不过,我有点惊讶的是,您没有收到任何与规范结果相关的异常。

回答by kaleb4eg

Use expect{}instead of expect().

使用expect{}代替expect()

回答by BroiSatse

get :indexwill never raise an exception - it will rather set response to be an 500 error some way as a real server would do.

get :index永远不会引发异常 - 它会像真实服务器那样以某种方式将响应设置为 500 错误。

Instead try:

而是尝试:

it 'raises CarBrandNotFound exception' do
  controller.params[:car_brand_id] = 0
  expect{ controller.car_brand }.to raise_error(Errors::CarBrandNotFound)
end