Home > OS >  Rails 4 - How to mock the exception with custom response using rspec?
Rails 4 - How to mock the exception with custom response using rspec?

Time:08-27

In rails 4, I am using rspec for writing a test cases. Currently I want to mock one service call which raises Exception and returns required(custom) output.

Eg:

allow(RestClient).to receive(:post).and_raise(User::APIError)

and its response should be like .and_return(error_response)

error_response is equal to an object which can be anything.

Please help me to write a spec for this condition.

CodePudding user response:

You can try using an instance double which responds to a particular method. Example:

api_error = instance_double(User::APIError, method_name: error_response)
allow(RestClient).to receive(:post).and_raise(api_error)

Hope that helps.

CodePudding user response:

I would mock it like this:

allow(RestClient).to receive(:post).and_raise(User::APIError, 'custom error message')

See docs about mocking errors

You can then test that the exception is raised with a specific message like this.

expect { method_calling_the_API }
  .to raise_error(an_instance_of(User::APIError)
  .and having_attributes(message: 'custom error message'))

See RSpec docs for error matcher.

  • Related