I had the same problem with Unit-Tests and Core Data:
First I ran into "Can't find model for store". I fixed this using this thread: Error running 'Cedar' unit tests from command line
Second I got the same error: "Failed to create file; code = 2"
Then I looked at the URLs and saw that:
The URL for the NSPersistentStoreCoordinator and the NSManagedObjectModel are quite diffrent. But only when I do Unit-Testing and only after fixing the first error.
Usually the model is in "/some/path/<DataModelFile>.app/<DataModel>.momd/
The sqlite is in "some/path/Documents/<SQLiteFile>.sqlite
So I use the following code to get the correct URLs in both testing and running:
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSURL *modelURL = [bundle URLForResource:@"WinNav" withExtension:@"momd"];
basePath = @"";
NSArray *arr = [modelURL pathComponents];
for (int i=0; i<[arr count]-2; i++) {
basePath = [basePath stringByAppendingString:[arr objectAtIndex:i]];
if (i > 0) basePath = [basePath stringByAppendingString:@"/"];
}
NSLog(@"modelURL: %@", modelURL);
NSURL *storeUrl = [NSURL fileURLWithPath:[basePath stringByAppendingString:@"/Documents/Locations.sqlite"]];
If I remember right then I had to create the "Documents" folder where the sqlite file is stored.
Any comments / suggestions if this works for you or how to do it better are appreciated.