Cannot test stub responses with Alamofire

1k Views Asked by At

I'm trying to test Alamofire request stubbing the responses using OHHTTPStubs and Quick/Nimble. However Alamofire doesn't process the response and consequently I cannot test the result.

My current testing code is:

OHHTTPStubs.stubRequestsPassingTest({$0.URL!.host == "authenticate.com"}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
                let obj = ["status": "ok", "data": "something"]
                return OHHTTPStubsResponse(JSONObject: obj, statusCode:200, headers:nil)
            })

            let gitdoRepository: GitdoRepository = GitdoRepository()
            waitUntil(timeout: 2, action: { (done) -> Void in
                gitdoRepository.authenticate("http://authenticate.com", completion: { (error) -> () in
                    expect(error).toNot(beNil())
                })
                NSThread.sleepForTimeInterval(2)
                done()
            })

Where I've added a breakpoint in the stub closure to make sure that Alamofire executes the request and the closure is called. However the response closure of the client is never called and consequently the test doesn't run successfully. This is the authenticate method:

func authenticate(authenticationUrl: String, completion: (error: OauthError?) -> ()) {
    Alamofire.request(.POST, authenticationUrl).responseJSON { (request: NSURLRequest?, response: NSHTTPURLResponse?, object: AnyObject?, error: NSError?) -> Void in
        if let error = error {
            completion(error: .HTTPError(error))
        }
        else if let object = object {
            if let oauth = self.oauthParser(object) {
                self.oauth = oauth
                completion(error: nil)
            }
            else {
                completion(error: .UnparseableCredentials)
            }
        }
        else {
            completion(error: .ResponseWithoutCredentials)
        }
    }
}

Is there anything I'm doing wrong with Alamofire? Thanks in advance

1

There are 1 best solutions below

0
On

I had the same problem. After scratching my head for two days, i think i found the solution. You can't call expect(self.error).toNot(beNil()) in in your completion block, but instead, just call it after your request code. Like this:

gitdoRepository.authenticate("http://authenticate.com", completion: { (error) -> () in
                self.error = error
            })
expect(self.error).toEventuallyNot(beNil(), timeout: 3)

Of course you have to declare "error" variable. Please try it and let me know if that works.