Ruby on Rails: the best way to test a failed third-party API call

I'm calling a third party web service right now as part of my application. For this I use RestClient stone. There are a ton of tools available to ensure that it doesn't matter.

I am curious that I have good enough tests, nothing special, I can imitate how my application reacts when a third-party web service is unavailable for any reason. Whether I have exceeded the speed limit or timeout due to latency / network complications, I just want to have something like an HTTP status code and check what my application does in this case.

What is the best way to do this with Test :: Unit? Right now, a call to a third party is encapsulated inside one of my controllers. I have a simple module with some wrapper methods for different endpoints of a remote service. I just want to make sure my application does the right thing when the service is or is unavailable.

Does it use additional infrastructure next to Test :: Unit, which can drown out the correct way to do this? Obviously, I can’t get the network timeout and start hacking things like IPtables for test only, it’s not worth the time. I’m sure this problem has been solved a million times since integrating things like Facebook and Twitter into web applications is so popular these days. How do you test the error when reaching these APIs in a reliable / controlled format?

+6
source share
2 answers

I would recommend using something like webmock to make fun of all your http requests (and not just mock a failed request); this will greatly speed up your test suite, rather than actually attacking a third-party service every time you run tests.

Webmock supports Rest Client and Test :: Unit. Just put this code in your test/test_helper.rb file:

 require 'webmock/test_unit' 

As an example, to check the network timeout:

 stub_request(:any, 'www.example.net').to_timeout RestClient.post('www.example.net', 'abc') # ===> RestClient::RequestTimeout 
+5
source

railscast: 291 (subscriber only) talks about testing with a VCR and rspec (I know, not a test: Unit)

Anyway, you can learn VCR for this kind of thing.

+1
source

Source: https://habr.com/ru/post/900001/


All Articles