How to Test (Rspec) a Http Request That Takes Too Long

how do I test (rspec) a http request that takes too long?

If you purely care about Net::HTTP raising a Timeout::Error, you could always just force it to return the error with a mock, here is a good compilation of various things you can use with RSpec.

It would depend on your exact Net::HTTP request, but something such as Net::HTTP.should_receive(:request_get).and_raise(Timeout::Error) would skip any networking calls and just raise the error immediately.

Ruby RSpec Net:HTTP - How to test request payload is as expected while mocking a response

A popular way to do this is called VCR. You can find a lot of docs and a RailsCast on the project web site. Basically, it works like this:

  • You set VCR on "record mode".
  • You make a request to the real backend. VCR records the request and response.
  • You set VCR to "playback" mode.
  • When you run your tests, you can use VCR to make assertions about the request and response (in other words, that it matches your expectations).

It's a robust way to verify that HTTP requests are doing exactly what you want them to.

How can I test (with RSpec) that an HTTP request is send in Rails (as part of an unit test)?

Normally I use VCR for testing requests and responses. With this you can record the request and response made in your code. The main purpose of VCR is to speed up your test suite and make it more robust against changes in third party systems.

In your case you could setup unit tests where you pass params to the activate and deactivate methods and test against the responses you are expecting from the inputs.

You could (although I cannot recommend this) parse the vcr cassette for the part where the request url is located and match it against your expectation.

rspec testing that api call increments a counter

Probably several ways to solve it. I tend to call .reload on my object if I want updated values for it and don't care what exactly is happening inside the object itself.

it "counts how many times a client has pulled its config" do
client = Endpoint.last
config_count = client.config_count
post '/api/config', node_key: client.node_key
client.reload
expect(client.config_count).to eq(config_count + 1)
end

Mocking request timeout in RSpec

You can use #and_raise to mock an error.

allow(RequestObject).to receive(:post).and_raise(SomeError)

That should allow you to test that code path.

Here's a link to the rspec docs.



Related Topics



Leave a reply



Submit