iosunit-testingcore-datansmanagedobjectquick-nimble

NSManagedObjects properties always nil with Quick-Nimble


In the past, I've tested my CoreData layer in XCTests by setting up a managed object context in memory as described in this post. Basically:

class func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
        let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!
        let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)

        do {
            try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
        } catch {
            print("Adding in-memory persistent store failed")
        }

        let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

        return managedObjectContext
    }

Recently I've been using Quick/Nimble with the same setup and in the expect statements it always reads the properties of my NSManagedObject as being nil, even though they have values when I debug the tests. For example, where savedItem is an NSManagedObject instance, when I store its property in a variable, it will pass:

let name = savedItem.name
it("should have a name") {
    expect(name).to(equal(item.name))
}

but if I test savedItem.name directly:

it("should have a name") {
    expect(savedItem.name).to(equal(item.name))
}

the test fails with the message: expected ... got <nil>

How can I test my CoreData objects directly using Quick/Nimble?


Solution

  • The odd behaviour I was experiencing seems to have been related to the fact that I was initializing my NSManagedObject directly inside the context closure but before the it closure. When I initialized it in a beforeEach closure (inside of context) it behaved as expected.