How to test exception raising in Rails/RSpec?

前端 未结 3 1749
梦毁少年i
梦毁少年i 2020-12-08 18:10

There is the following code:

def index
    @car_types = car_brand.car_types
end

def car_brand
    CarBrand.find(params[:car_brand_id])
    rescue ActiveReco         


        
相关标签:
3条回答
  • 2020-12-08 18:35

    Use expect{} instead of expect().

    0 讨论(0)
  • 2020-12-08 18:36

    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.

    0 讨论(0)
  • 2020-12-08 18:49

    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
    
    0 讨论(0)
提交回复
热议问题