4

BEGIN_SPEC END_SPEC在我的规范文件的块中定义了一些我经常重用的辅助块。例如断言某个对话框出现:

void (^expectOkAlert) (NSString *, NSString *) = ^void(NSString *expectedTitle, NSString *expectedMessage) {
    UIAlertView *alertView = [UIAlertView mock];
    [UIAlertView stub:@selector(alloc) andReturn:alertView];
    [[alertView should] receive:@selector(initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:)
                      andReturn:alertView
                  withArguments:expectedTitle,expectedMessage,any(),@"OK",any()];
    [[alertView should] receive:@selector(show)];
};

我想在其他几个规范文件中重用这个块。这是否像我们通常在 Ruby 世界中使用规范助手和 rspec 那样可能?

你如何管理你的全球规范助手?

4

1 回答 1

2

你可以

  • 在其他单元测试包含的公共标头中声明expectOkAlert为全局变量

    extern void (^expectOkAlert) (NSString *, NSString *);
    
  • expectOkAlert在一个KWSpec类别中声明,您仍然需要一个公共标头,该标头包含在您需要使用它的单元测试中

    @implementation KWSpec(Additions)
    + (void)expectOkAlertWithTitle:(NSString*)title andMessage:(NSString*)message;
    @end
    

    你像这样使用它:

    it(@"expects the alert", %{
        [self expectOkAlertWithTitle:@"a title" andMessage:@"a message"];  
    });
    
  • 或创建一个自定义匹配器并使用它来断言:

    @interface MyAlertMatcher: KWMatcher
    - (void)showOKAlertWithTitle:(NSString*)title andMessage:(NSString*)message;
    @end
    

    并在您的测试中使用它,如下所示:

    it(@"expects the alert", %{
        [[UIAlertView should] showOkAlertWithTitle:@"a title" andMessage:@"a message"];  
    });
    

所有方法都要求您在单元测试目标可用标头中声明帮助程序,否则您将收到编译警告/错误。

于 2015-05-22T05:57:18.810 回答