我正在努力设置网络POST请求的简单存根。我已经尽可能多地从OHHTTPStubs文档和其他在线资源建模,但我想我必须遗漏一些东西。我希望看到基于onStubActivation
方法记录的存根调用。我的测试看起来像:
#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@domain.com"
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
客户端看起来像:
#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