如何在 Rails/RSpec 中测试异常引发? [英] How to test exception raising in Rails/RSpec?
本文介绍了如何在 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 对其进行测试.我的代码是:
I want to test it through RSpec. My code is:
it 'raises CarBrandNotFound exception' do
get :index, car_brand_id: 0
expect(response).to raise_error(Errors::CarBrandNotFound)
end
id 等于 0 的 CarBrand 不存在,因此我的控制器代码引发 Errors::CarBrandNotFound,但我的测试代码告诉我没有引发任何问题.我该如何解决?我怎么了?
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?
推荐答案
使用 expect{}
而不是 expect()
.
示例:
it do
expect { response }.to raise_error(Errors::CarBrandNotFound)
end
这篇关于如何在 Rails/RSpec 中测试异常引发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文