How to capture HTTP request object with WebMock


I got a question regarding writing of clean tests. I am using webmock to test something.

    WebMock.stub(:post, "").to_return do |request|

... setup code for sending the requests comes here ...

... expectations go here ...

The object I would like to assert at the end of my test method is the passed request that has been gathered when the HTTP client called the endpoint.

In Java I would probably go with some Atomic(HTTP::Request) request like structure, and then retrieve it at the end of the test (or just a regular HTTP::Request variable.

Is there anything better/more readable I could do to solve it in a more crystal way of things?

Thanks for any help!



I don’t follow why you want to get the response in the test. Stubs are used to remove the dependency of having a running http server so the code you are testing can be check without the server. The response is to be consumed by the code you are testing.

You can add expectations to the request object inside the stub and it works as expected. You can also just set it to a local variable which you check at the end of the spec, if you need access both to the request that the code sent and the return values of the code under test at the same time.

I was testing my lambda implementation, where I wanted to emulate the AWS Lambda HTTP endpoint and verify if my implementation send the right request to that endpoint… by staring at the code I figured out that there are easier ways of testing what I want.

If a test makes you uncomfortable or you need to jump through hoops to achieve what you want to tes, you are testing in a wrong way :slight_smile: happened here

thanks a bunch for your help!

1 Like