Skip to content

Best Practices: Question and Answer

vrclvrncknm edited this page Oct 3, 2013 · 3 revisions

Question: So one thing I want to do is write up some expectations that document and test the attributes my object will have. I have a pattern like below but it's not as DRY as I'd like. Could someone point me in the right direction as to how I might DRY this up or utilize the message related expectations to simplify these?

   it(@"has an assignable NSString attribute for name", ^{
        NSString *newStringValue = @"Some cool string.";
        company.name = newStringValue;
        [ [company.name should] equal:newStringValue];
    });
    
    it(@"has an assignable NSString attribute for note", ^{
        NSString *newStringValue = @"Some cool string.";
        company.note = newStringValue;
        [ [company.note should] equal:newStringValue];
    });

Answer: My current solution.

    it(@"has many assignable NSString attributes ...", ^{
        
        NSArray *attributeNames = [NSArray arrayWithObjects:@"email", @"facebookURL", @"firstName", @"homeAddressLine1", @"homeAddressLine2", @"homeCity", @"homeCountry", @"homeState", @"imageThumbURL", @"instantMessenger", @"lastName", @"position", @"twitter", @"workAddressLine1", @"workAddressLine2", @"workCity", @"workCountry", @"workState", nil];
        NSManagedObject *object = person;
        
        for (NSString *attributeName in attributeNames) {
            NSString *newStringValue = @"Some cool string.";
            NSString *settor = [NSString stringWithFormat:@"set%@:", [attributeName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[attributeName substringToIndex:1] capitalizedString]]];
            NSString *gettor = [NSString stringWithFormat:@"%@", attributeName];
            
            // http://stackoverflow.com/questions/7017281/performselector-may-cause-a-leak-because-its-selector-is-unknown
            #pragma clang diagnostic push
            #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [object performSelector:NSSelectorFromString(settor) withObject:newStringValue];
            [ [[person performSelector:NSSelectorFromString(gettor)] should] equal:newStringValue];
            #pragma clang diagnostic pop
        }
        
    });