Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test exception raising in Rails/RSpec?

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:

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?

like image 616
malcoauri Avatar asked Mar 03 '14 08:03

malcoauri


People also ask

How do you raise errors in Ruby?

Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).

What is allow in RSpec?

Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.


1 Answers

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.

like image 152
Jakob S Avatar answered Oct 02 '22 17:10

Jakob S