如何测试Rails/RSpec中的异常提升?

时间:2022-06-06 20:18:11

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不存在,因此我的控制器代码会引发错误::CarBrandNotFound,但我的测试代码告诉我,没有生成任何内容。我怎样才能修好它?我错了吗?

3 个解决方案

#1


61  

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 error for details.

有关细节,请参见Expect错误。

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

不过,我有点惊讶,您并没有发现任何异常冒泡到您的spec结果中。

#2


39  

Use expect{} instead of expect().

使用expect{}代替expect()。

#3


11  

get :index will 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

#1


61  

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 error for details.

有关细节,请参见Expect错误。

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

不过,我有点惊讶,您并没有发现任何异常冒泡到您的spec结果中。

#2


39  

Use expect{} instead of expect().

使用expect{}代替expect()。

#3


11  

get :index will 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