bobfet1
bobfet1

Reputation: 1633

How to test for API errors?

My rails app talks to a couple different APIs, and I'd like to write tests to make sure that errors are being handled properly in case there is a problem with a request. For example, if the service is down and not reachable.

Is there a way I can simulate an error coming back from a service even though it might be fine during the test?

Upvotes: 1

Views: 169

Answers (2)

jdl
jdl

Reputation: 17790

The webmock gem helps you with this. For your specific question scroll down to "Response with custom status message".

stub_request(:any, "www.example.com").to_return(:status => [500, "Internal Server Error"])

req = Net::HTTP::Get.new("/")
Net::HTTP.start("www.example.com") { |http| http.request(req) }.message # ===> "Internal Server Error"

I've used this gem with Rspec and Test::Unit. The biggest drawback is that the matching logic which decides what requests apply to a particular mock doesn't always work as you'd expect. It's a minor gripe though. The gem is a net-positive, and much better than trying to hit a live service from a test case.

Upvotes: 1

Esko Luontola
Esko Luontola

Reputation: 73655

You can use a mock instead of the real service, and make it give back an error.

Upvotes: 0

Related Questions