如何在 Rails/RSpec 中测试异常引发?

有以下代码:

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

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

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

Id 等于0的 CarBrand 不存在,因此我的控制器代码引发了 Errors: : CarBrandNotfound,但是我的测试代码告诉我没有引发任何错误。我该怎么补救?我做错了什么?

85489 次浏览

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.

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

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.

Instead try:

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

Use expect{} instead of expect().

Example:

it do
expect { response }.to raise_error(Errors::CarBrandNotFound)
end