I'm just starting out with stubbing requests to test async calls to an external API with iOS. I'm currently stuck with the following code and I can't figure out what's not working.
The very simple thing I'm trying to achieve is that if I get a 200 response from a website, I change the background color of my view to green, else I tint it red.
In the - (void)viewDidLoad
method of my view controller I'm calling the following method:
- (void)checkConnectivity {
NSURL *url = [NSURL URLWithString:@"http://www.example.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
self.currentBackgroundColor = [UIColor greenColor];
[self changeToBackgroundColor:self.currentBackgroundColor];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
self.currentBackgroundColor = [UIColor redColor];
[self changeToBackgroundColor:self.currentBackgroundColor];
});
}
}];
[task resume];
}
- (void)changeToBackgroundColor:(UIColor *)color {
self.view.backgroundColor = color;
}
My Kiwi spec looks like this:
#import "Kiwi.h"
#import "Nocilla.h"
#import "TWRViewController.h"
@interface TWRViewController ()
@property (strong, nonatomic) UIColor *currentBackgroundColor;
- (void)checkConnectivity;
- (void)changeToBackgroundColor:(UIColor *)color;
@end
SPEC_BEGIN(KiwiSpec)
describe(@"When the app launches", ^{
context(@"check if internet is available", ^{
beforeAll(^{
[[LSNocilla sharedInstance] start];
});
afterAll(^{
[[LSNocilla sharedInstance] stop];
});
afterEach(^{
[[LSNocilla sharedInstance] clearStubs];
});
it(@"should display a green background if there is connectivity", ^{
stubRequest(@"GET", @"http://www.example.com/").andReturn(200);
TWRViewController *vc = [[TWRViewController alloc] initWithNibName:@"TWRViewController" bundle:nil];
[vc checkConnectivity];
[[vc.currentBackgroundColor shouldEventually] equal:[UIColor greenColor]];
});
});
});
SPEC_END
I don't know what I'm doing wrong, but it keeps failing. Any idea?
Seems like your asynchronous matcher is incomplete.
You need to wrap the subject of an async matcher with expectFutureValue like this:
For future reference, when you adding an async matcher to a primitive like a BOOL you need to add theValue on top of that, like this:
Hope it helps