Ott*_*tto 14 objective-c ios kiwi
我有一些重复的规格,我想干.常用功能不适合移动到beforeEach
块中.本质上,它是对象创建,并且12个对象中的每一个都是4行,我想将这4行转换为单个函数调用.
我在哪里可以将辅助函数放入Kiwi规范中?
在RSpec中我可以放在def
spec块之间,但这似乎不可能在这里.我甚至试过跳过SPEC_END
宏并自己添加内容,所以我可以在@implementation中添加函数,SPEC_BEGIN
但这似乎也不起作用.
更正 ......我可以通过手动编码SPEC_END
宏来管理一些有用的东西.我结束了错误的位置.但是,它仍然失败,因为该方法不在@interface
.
Dou*_*ist 34
在SPEC_BEGIN之后创建辅助函数作为块:
SPEC_BEGIN(MySpec)
NSDate* (^dateFromString) (NSString *) = ^NSDate* (NSString *dateString) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateFormat:@"MM-dd-yyyy"];
return [dateFormatter dateFromString:dateString];
};
describe(@"something", ^{
NSDate *checkDate = dateFromString(@"12-01-2005");
...
});
SPEC_END
Run Code Online (Sandbox Code Playgroud)
您还可以在SPEC_BEGIN()
范围之上创建直接C函数.
NSString *makeAString () {
return @"A String";
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您具有将在多个Spec文件中使用的辅助函数,请将这些函数放在单独的文件中并导入标题.我发现这是清理我的规格的好方法.
supermarin建议采用以下方法:
@implementation KWSpec(Additions)
+ (void)myHelperMethod:(Car*)car {
[[car shouldNot] beNil];
};
@end
SPEC_BEGIN(FooBarSpec)
describe(@"A newly manufactured car", ^{
it(@"should not be nil", ^{
[self myHelperMethod:[CarFactory makeNewCar]];
});
});
SPEC_END
Run Code Online (Sandbox Code Playgroud)
道格建议的另一个选择是:
SPEC_BEGIN(FooBarSpec)
void (^myHelperMethod)(Car*) = ^(Car* car){
[[car shouldNot] beNil];
};
describe(@"A newly manufactured car", ^{
it(@"should not be nil", ^{
myHelperMethod([CarFactory makeNewCar]);
});
});
SPEC_END
Run Code Online (Sandbox Code Playgroud)
关于它的好处是它非常适合异步场景:
SPEC_BEGIN(FooBarSpec)
__block BOOL updated = NO;
void (^myHelperAsync)() = ^()
{
[[expectFutureValue(theValue(updated)) shouldEventually] beYes];
};
describe(@"The updater", ^{
it(@"should eventually update", ^{
[[NSNotificationCenter defaultCenter] addObserverForName:"updated"
object:nil
queue:nil
usingBlock:^(NSNotification *notification)
{
updated = YES;
}];
[Updater startUpdating];
myHelperAsync();
});
});
SPEC_END
Run Code Online (Sandbox Code Playgroud)
最后,如果您的帮助方法驻留在另一个类中,gantaa建议一个聪明的黑客:
@interface MyHelperClass
+(void)externalHelperMethod:(id)testCase forCar:(Car*)car
{
void (^externalHelperMethodBlock)() = ^(){
id self = testCase; //needed for Kiwi expectations to work
[[car shouldNot] beNil];
};
externalHelperMethodBlock();
}
@end
SPEC_BEGIN(FooBarSpec)
describe(@"A newly manufactured car", ^{
it(@"should not be nil", ^{
[MyHelperClass externalHelperMethod:self forCar:[CarFactory makeNewCar]];
});
});
SPEC_END
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2792 次 |
最近记录: |