OHHTTPStubs icon indicating copy to clipboard operation
OHHTTPStubs copied to clipboard

Manually triggering a response when ready, instead of relying on request time

Open ndbroadbent opened this issue 9 years ago • 3 comments

Would it be possible to stall responses, and trigger when I want the response to be sent?

My situation is that I'm stubbing a "post" upload to AWS, which starts in the background as soon as a user selects a photo. Then the user types in the post description and taps "submit". After this, I need to write some tests to ensure that the "uploading" view is visible, and to ensure that the upload can be cancelled.

Right now I'm setting the request time to 10 seconds, which gives us enough time to run these tests. But it would be great if I could store the OHHTTPStubsResponse in a variable, and then call something like respond() as soon as the tests are finished. I'm not a big fan of relying on a fixed request time, because it makes our tests slow, and it also might not be long enough if we're running on a slow CI machine.

I took a quick a look at the code, and I think I can refactor it to make this possible.

Would you be interested in adding this feature?

ndbroadbent avatar Apr 11 '16 20:04 ndbroadbent

Here's what I hacked together: https://github.com/hdwr/OHHTTPStubs/commit/c394ba28312133691b9d6ff7ebbb82238ea28048

Sorry it's pretty ugly, but it works for us! This is how I'm using it in our app:

    lazy var pendingS3Uploads = [OHHTTPStubsResponse]()
    func setupS3UploadsStub() {
        stub(isHost("s3-us-west-2.amazonaws.com") && pathStartsWith("/uploads")) { req in
            let response = OHHTTPStubsResponse(data: NSData(), statusCode: 200, headers: nil)
                           .shouldWait(true)
            self.pendingS3Uploads.append(response)
            return response
        }
    }

    class func sendS3UploadResponses() {
        for response in sharedInstance.pendingS3Uploads {
            response.respondNow()
        }
        sharedInstance.pendingS3Uploads.removeAll()
    }

So in the KIF test case I can call sendS3UploadResponses() when I'm ready to send the response.

ndbroadbent avatar Apr 11 '16 21:04 ndbroadbent

Seems Great and really interesting indeed! This could also interest @lukabernardi who requested it in #53 a while back

I'd make the sendResponseHandler property private instead of public (as it's set by the framework and it's supposed to be called by the respondNow public API already) but otherwise seems great.

Could you maybe submit a PR for this to propose the code and its associated Unit Tests?

AliSoftware avatar May 05 '16 12:05 AliSoftware