Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell MagicalRecord to not use the file based Core Data but an in memory setup?

I followed this great article to get into Unit Testing regarding Core Data. The setup seems simple and involves just some view lines of code.

- (void)setUp;
{
    [MagicalRecord setDefaultModelWithClass:[self class]];
    [MagicalRecord setupCoreDataStackWithInMemoryStore];
}

- (void)tearDown;
{
    [MagicalRecord cleanUp];
}

- (void)testSomeCalculationOnMyEntity;
{
    NSNumber *count = [MyEntity MR_numberOfEntities];
    // STAssert([testEntity customCalculation] == expectedValue, @"expected a good calculation");
}

@end

The problem is, that each time I for example check for the amount of entities in the in memory set up of Core Data by calling [MyEntity MR_numberOfEntities] (like above), I get the amount of objects, which are stored in the file based setup which are a couple of thousand objects. How does this happen? I mean the second line in setUp indicates the in memory one, doesn't it? And this case should return 0 as the amount of objects stored.

Thanks for any suggestions!

Edit:

@casademora put me on the right track. The following works setup works fine for me now.

- (void)setUp;
{
    [MagicalRecord cleanUp]; // This solved the mystery.

    // I don't now why I had to remove this line, though.
    // [MagicalRecord setDefaultModelWithClass:[self class]];

    [MagicalRecord setupCoreDataStackWithInMemoryStore];
}

- (void)tearDown;
{
    [MagicalRecord cleanUp];
}

- (void)testSomeCalculationOnMyEntity;
{
    NSNumber *count = [MyEntity MR_numberOfEntities];
    // STAssert([testEntity customCalculation] == expectedValue, @"expected a good calculation");
}

@end
like image 832
Aufwind Avatar asked Jul 31 '12 11:07

Aufwind


2 Answers

The method used to setup Core Data here should not ever load a file based store. If you step into it using the debugger, you should see that it initializes a persistent store coordinator using the NSInMemoryStore type...eventually.

My guess as to why this happens could be because you did not add a cleanUp call to a previous test case, causing a previous core data stack, or persistent store, to hang around into this test.

This is the exact code setup I use to unit test core data all the time, and it has never loaded an unintended persistent store for me. When you debug into the method, make sure to run this command:

po [self persistentStores]

When you get to the loading of the persistent store coordinator. If there are existing stores, this will at least verify that there are some pre-existing stores hanging around.

like image 123
casademora Avatar answered Nov 09 '22 17:11

casademora


You could also add the following which is performed once on class initialisation. This worked for me.

 +(void)setUp
   {
           [MagicalRecord cleanUp];
   }
like image 29
Ajaxharg Avatar answered Nov 09 '22 17:11

Ajaxharg