I am having trouble for the matcher to catch the exception. The controller method simply doing a REST call and get the fruit with the id and I want to test when REST give me an error respond which in rails is the JSON::ParserError. I want to test this case, so I stub out the REST call and raise the exception.
I know the fact that the stubbing work since I am getting that exact error. I believe that I just need a matcher to catch the error when calling the get
In Controller
def show
@fruit = FruitsService::Client.get_fruit(params[:id])
end
spec/controller/fruits_controller_spec.rb
describe '#show' do
before do
context 'when a wrong id is given' do
FruitsService::Client.any_instance
.stub(:get_fruit).with('wrong_id')
.and_raise(JSON::ParserError)
end
it 'receives 404 error code' do
get :show, {id: 'wrong_id'} <------ I think I might need a matcher for this ?
expect(FruitsService::Client.get_fruit('wrong_id')).to raise_error(JSON::ParserError)
end
end
This giving this
Failure/Error: get :show, {id: 'wrong_id'}
JSON::ParserError:
JSON::ParserError
When you want to test behavior, such as the raising of errors, you need to pass a block to expect
instead of a parameter, as in:
it 'receives 404 error code' do
expect { get :show, {id: 'wrong_id'} }.to raise_error(JSON::ParserError)
end