Skip to content

Instantly share code, notes, and snippets.

@RawToast
Created October 2, 2015 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RawToast/b484d70757211ccde686 to your computer and use it in GitHub Desktop.
Save RawToast/b484d70757211ccde686 to your computer and use it in GitHub Desktop.
In memory CoreData configuration for unit testing
import Foundation
import CoreData
func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let managedObjectModel = NSManagedObjectModel.mergedModelFromBundles([NSBundle.mainBundle()])!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try persistentStoreCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
} catch {
assertionFailure("Unable to setup coredata")
}
let managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}
@RawToast
Copy link
Author

RawToast commented Oct 2, 2015

Usage:

let context = setUpInMemoryManagedObjectContext()
let myObject = NSEntityDescription.insertNewObjectForEntityForName("MyObject", inManagedObjectContext: context) as! MyObject

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment