Corbin
Corbin

Reputation: 162

OHHTTPStubs with AFNetworking in Cedar

I am struggling to set up a simple stub of a network POST request. I have modeled as much as I can from the OHHTTPStubs docs and other resources online, but I think I must be missing something. I would like to see the stub called based on the logging by the onStubActivation method. My test looks like:

#import "Cedar.h"
#import "OHHTTPStubs.h"
#import "Client.h"

SPEC_BEGIN(Spec)

describe(@"Client", ^{
    __block Client *subject;
    __block __weak id<OHHTTPStubsDescriptor> stub;

    beforeEach(^{
        subject = [[Client alloc] init];
        stub = [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
            return YES;
        } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
            return [OHHTTPStubsResponse 
                        responseWithJSONObject:@{} 
                        statusCode:200 
                        headers:@{ @"Access-Token": @"new-token"}];
        }];
        stub.name = @"success-stub";

        [OHHTTPStubs onStubActivation:
            ^(NSURLRequest *request, id<OHHTTPStubsDescriptor> stub) {
                NSLog(@"%@ stubbed by %@.", request.URL, stub.name);
        }];
    });

    describe(@"-signInWithUsername:Password:SuccessBlock:FailureBlock:", ^{
       subjectAction(^{
            [subject signInWithUsername:@"[email protected]"
                               Password:@"password"
                           SuccessBlock:^void(){NSLog(@"GREAT-SUCCESS");}
                           FailureBlock:^void(){NSLog(@"GREAT-FAILURE");}];
            });
        context(@"when the user/password is valid", ^{
            it(@"should update the auth token", ^{
                subject.token should equal(@"new-token");
            });
        });

    });
});

SPEC_END

Client looks like:

#import "Client.h"
#import "AFNetworking.h"

@interface Client ()

@property (nonatomic) NSString *token;
@property (nonatomic) AFHTTPRequestOperationManager *manager;

@end

@implementation Client

- (instancetype)init
{
    self = [super init];
    self.manager = [[AFHTTPRequestOperationManager alloc] init]];
    return self;
}

- (void)signInWithUsername:(NSString *)username
                  Password:(NSString *)password
              SuccessBlock:(void (^)())successBlock
              FailureBlock:(void (^)())failureBlock;
{
    [self.manager POST:@"http://localhost:3000/auth/sign_in" 
            parameters:nil 
               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                   NSLog(@"JSON: %@", responseObject);
                   successBlock();
    }         
               failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                   NSLog(@"Error: %@", error);
                   failureBlock();
    }];
}

@end

Upvotes: 1

Views: 164

Answers (0)

Related Questions