TDD-ing your Realm objects in Xcode Playgrounds

Published on: Apr 05, 2017

iOS Swift TDD Realm

In 2 previous posts, I’ve shown how to TDD and how to use 3rd party frameworks in Xcode Playgrounds. This one kinda ties them together.

If you’ve never used Realm Mobile Database before, head over to their Swift documentation pages. In short, it is a fast, open-source alternative to SQLite and CoreData — allows you to store your data fast in a cross-platform format. There is also a Realm Browser that can be downloaded from the Mac App Store.

The Task object and TestCase

Let’s go through this one step at a time.

Import PlaygroundWrapper and RealmSwift

As mentioned in "Using 3rd party frameworks in Xcode Playgrounds", this technique allows us to bring Realm support into the playgrounds.

Task realm object

I’ve created a simple realm object with one property — realm objects must have at least one property. In my case this an uuid that gets a randomly generated string when created.

class Task: Object {
    dynamic var uuid = UUID().uuidString


As described in "TDD in Xcode Playgrounds", I’ve created a subclass of XCTestCase and run a test suite.

The class also contains 2 properties that will help with the testing.

class TaskTests: XCTestCase {
    var realm: Realm!
    var task: Task!


The setup

The “magic” here is the use of in memory Realm databases with a random identifier. This ensures that a new fresh realm is created before each test.

Setting the Realm.Configuration.defaultConfiguration allows us to not having to store the configuration for later use — we can simply address the realm as Realm().

override func setUp() {
    Realm.Configuration.defaultConfiguration = 
        Realm.Configuration(inMemoryIdentifier: UUID().uuidString)

    task = Task()
    realm = try! Realm()
    try! realm.write {

The test: testSetup()

Fairly straigtforward — we’re testing that we have one and only one realm objects of type Task.

func testSetup() {
    let tasks = try! Realm().objects(Task.self)
    XCTAssertEqual(tasks.count, 1)

From here onwards, the world is your oyster…

The project can be found on github:

But is it fast?

Oh yes, it’s fast: Realm was designed and built for performance.

Last but not least, imagine TDD-ing with Core Data, Playgrounds or not. 🤓

Update April 5th

The Video of my “TDD in Xcode Playgrounds” lighthing talk at @iOSConLondon can be found here. It covers the subject of this article as well as others.