Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper functions in Kiwi specs

I have a few repetitive specs that I would like to DRY up. The common functionality doesn't lend itself to moving into a beforeEach block. Essentially, it's object creation and is 4 lines for each of 12 objects, I'd like to turn those 4 lines into a single function call.

Where can I put helper functions in a Kiwi spec?

In RSpec I can just put def between spec blocks, but that doesn't appear to be possible here. I've even tried skipping the SPEC_END macro and adding that content myself so I could add functions inside the @implementation from SPEC_BEGIN but that doesn't seem to work, either.

Correction... I can manage something that kind of works with hand-coding the SPEC_END macro. I had the end } mis-placed. But still, it fails, because the method isn't in the @interface.

like image 437
Otto Avatar asked Jun 25 '12 22:06

Otto


2 Answers

Create your helper function as a block just after the 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
like image 145
Doug Sjoquist Avatar answered Nov 06 '22 03:11

Doug Sjoquist


You could also create a straight C function above the SPEC_BEGIN() scope.

NSString *makeAString () {
    return @"A String";
}

Or if you have helper functions that will be used across several Spec files, place these functions in a separate file and import the header. I've found this to be a great way to clean up my Specs.

like image 8
bearMountain Avatar answered Nov 06 '22 03:11

bearMountain