How to test exception raising in Rails/RSpec?

Ruby on-RailsRubyRspec

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use expect{} instead of expect().

Example:

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

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmalcoauriView Question on Stackoverflow
Solution 1 - Ruby on-Railskaleb4egView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJakob SView Answer on Stackoverflow
Solution 3 - Ruby on-RailsBroiSatseView Answer on Stackoverflow