Skip to content

Instantly share code, notes, and snippets.

@benvium
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save benvium/fc51be00dc9da231b0cf to your computer and use it in GitHub Desktop.

Select an option

Save benvium/fc51be00dc9da231b0cf to your computer and use it in GitHub Desktop.
Inherit TestCase classes from this to setup and tearDown a SQLite-backedMagicalRecord core data stack on each test.The SQLite file itself will be deleted between runs.Test cases should use the context provided on self.context. Note that this has taken many tries to get right! Just deleting the files sometimes resulted in the data being retained …
#import <XCTest/XCTest.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
/**
Inherit XCTest TestCase classes from this to setup and tearDown a SQLite-backed
MagicalRecord core data stack on each test.
The SQLite file itself will be deleted between runs.
Test cases should use the context provided here
*/
@interface MagicalRecordTestCase : XCTestCase
@property(nonatomic, strong) NSManagedObjectContext *context;
@end
#import <CoreData/CoreData.h>
#import "MagicalRecordTestCase.h"
#import "MagicalRecord.h"
@implementation MagicalRecordTestCase
- (void)setUp {
[super setUp];
[MagicalRecord setupCoreDataStack];
self.context = [NSManagedObjectContext MR_defaultContext];
}
- (void)tearDown {
[super tearDown];
// Save changes - so they don't get re-saved later
[self.context MR_saveToPersistentStoreAndWait];
// http://stackoverflow.com/questions/14069563/clean-remove-a-database-in-magicalrecord
NSString *dbStore = [MagicalRecord defaultStoreName];
NSURL *storeURL = [NSPersistentStore MR_urlForStoreName:dbStore];
NSURL *walURL = [[storeURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sqlite-wal"];
NSURL *shmURL = [[storeURL URLByDeletingPathExtension] URLByAppendingPathExtension:@"sqlite-shm"];
NSError *error;
for (NSURL *url in @[storeURL, walURL, shmURL]) {
if ([[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
if (![[NSFileManager defaultManager] removeItemAtURL:url error:&error]) {
NSLog(@"An error has occurred while deleting %@ at %@ error %@", dbStore, url, error);
break;
}
}
}
[MagicalRecord cleanUp];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment