Renato Rodrigues
Renato Rodrigues

Reputation: 1038

UICollectionViewCell subviews not being updated on unit test

I have a test where I want to load a UICollectionViewCell (CustomCollectionViewCell), pass some data to it and check if the labels of the cell are updated with this data.

cell.nameLabel is a UILabel of the cell and the method setText is called but the text itself is never updated.

cell.nameLabel.text returns always the initial text defined in the xib.

The label is defined as follows:

@property (nonatomic, weak) IBOutlet UILabel *nameLabel;

And the spec:

SPEC_BEGIN(CustomCollectionViewCellSpec)

describe(@"CustomCollectionViewCell", ^{

    __block CustomCollectionViewCell *cell = nil;
    __block CustomCollectionViewCellData *cellData = nil;

    beforeEach(^{

        NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@"CustomCollectionViewCell"
                                                         owner:self
                                                       options:nil];

        for (id object in objects) {

            if ([object isKindOfClass:[CustomCollectionViewCell class]]) {

                cell = (CustomCollectionViewCell *)object;

                break;
            }
        }

        cellData = [[CustomCollectionViewCellData alloc] init];
        cellData.name = @"Custom name";
    });

    afterEach(^{

        cell = nil;
        cellData = nil;
    });

    it(@"should populate the views with the cell data", ^{

        [[cell.nameLabel should] receive:@selector(setText:)
                           withArguments:cellData.name];

        [cell configureWithCellData:cellData];

        [[cell.cellData should] equal:cellData];

        [[cell.nameLabel.text should] equal:cellData.name];
    });
});

SPEC_END

Upvotes: 0

Views: 251

Answers (1)

wolffan
wolffan

Reputation: 1104

The problem is how are you creating the cell. You can't alloc init a cell or get the nib. You ask a collection for it.

For collections you need:

    UICollectionView *collection = [[UICollectionView alloc] init];
    UICollectionCell *cell = [collection dequeueReusableCellWithReuseIdentifier:@"yourCellIdentifier" forIndexPath:0];

After this, you will be able to get your cell and modify it without having all it's properties as nil properties.

Upvotes: 0

Related Questions