Kiwi で NSURLConnection の非同期テスト

JSON API を NSURLConnection を使って call している場合の Kiwi でのテスト方法。

describe(@"HogeAPI", ^{
    describe(@"createDeck", ^{
        context(@"when cant't connect", ^{
            it(@"should return nil", ^{
                __block id ret;
                User* user = [User mock];
                [[user should] receive:@selector(userID) andReturn:theValue(@"3")];
                [[user should] receive:@selector(secret) andReturn:theValue(@"secret")];
            
                HogeAPI* api = [[HogeAPI alloc] init];
                [api stub:@selector(createConnection:) andReturn:nil];
                [api createDeck:user block:^(id object, NSError* error) {
                    ret = object;
                }];
                [[expectFutureValue(ret) shouldEventually] beNil];
            });
        });
        context(@"when http status 500", ^{
            it(@"should return nil", ^{
                __block Deck* deckID;
                User* user = [User mock];
                [[user should] receive:@selector(userID) andReturn:theValue(@"3")];
                [[user should] receive:@selector(secret) andReturn:theValue(@"secret")];
                
                
                HogeAPI* api = [[HogeAPI alloc] init];
                NSURLConnection* conn = [[NSURLConnection alloc] init];
                [api stub:@selector(createConnection:) andReturn:conn];
                [api stub:@selector(getJSONData) andReturn:[@"{\"id\": 12}" dataUsingEncoding:NSUTF8StringEncoding]];
                [api createDeck:user block:^(id object, NSError* error) {
                    deckID = object;
                }];
                NSHTTPURLResponse* res = [NSHTTPURLResponse mock];
                [res stub:@selector(statusCode) andReturn:theValue(500)];
                [api connection:conn didReceiveResponse:res];
                [[expectFutureValue(deckID) shouldEventually] beNil];
            });
        });
        context(@"when success", ^{
            it(@"should return a new deck_id", ^{
                __block Deck* deckID = nil;
                User* user = [User mock];
                [[user should] receive:@selector(userID) andReturn:theValue(@"3")];
                [[user should] receive:@selector(secret) andReturn:theValue(@"secret")];

                HogeAPI* api = [[HogeAPI alloc] init];
                NSURLConnection* conn = [[NSURLConnection alloc] init];
                [api stub:@selector(createConnection:) andReturn:conn];
                [api stub:@selector(getJSONData) andReturn:[@"{\"id\": 12}" dataUsingEncoding:NSUTF8StringEncoding]];
                [api createDeck:user block:^(id object, NSError* error) {
                    deckID = object;
                }];
                [api connectionDidFinishLoading:conn];
                [[expectFutureValue(deckID) shouldEventually] equal:@"12"];
            });
        });
    });
});