4

I've defined some helper blocks within the BEGIN_SPEC END_SPEC block in my spec file that I reuse quite often. E.g. asserting that a certain dialog shows up:

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)];
};

I'd like to reuse this block over several other spec files. Is that somehow possible like we normally do it with spec helpers and rspec in the Ruby world?

How do you manage you global spec helpers?

mikrobi
  • 291
  • 1
  • 3
  • 11

1 Answers1

2

You can

  • declare expectOkAlert as a global variable, in a common header that gets included by the other unit tests

    extern void (^expectOkAlert) (NSString *, NSString *);
    
  • or declare expectOkAlert in a KWSpec category, you'll still need a common header that gets included in the unit tests you need to use it

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

    and you use it like this:

    it(@"expects the alert", %{
        [self expectOkAlertWithTitle:@"a title" andMessage:@"a message"];  
    });
    
  • or create a custom matcher and use that to assert:

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

    and use it in your tests like this:

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

All approaches require you declare the helper in a unit-test target available header, otherwise you'll get compilation warnings/errors.

Cristik
  • 30,989
  • 25
  • 91
  • 127