Search code examples
ruby-on-railsrubyexceptionrspecrest-client

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


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.


Solution

  • 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.