How to test raise_error matcher if it gets an error

Category: Ruby :: Published at: 23.06.2021

The problem with raise_error matcher in RSpec is common and it can be fixed in easy way.

Let's say we have situation like below:

subject(:service_call) { }

it { expect(service_call).to raise_error(CarDatabaseConnectionError) }

If we call it like this it will get us an error.

  1) CarUpdateService when fail 
     Failure/Error: raise CarDatabaseConnectionError
       Can't connect with a custom car database.

Why it didn't pass the spec?

The problem is here:


If we call the subject in parentheses it will read full service in the beginning and it won't even check our matcher.

The resolution is to call our subject as a block:

subject(:service_call) { }

it { expect { service_call }.to raise_error(CarDatabaseConnectionError) }

If we do it like this, our test will pass withour problem :)

- Click if you liked this article

Views: 74