TDD-ing your @Realm objects in Xcode Playgrounds

Paul Ardeleanu
Paul Ardeleanu’s Blog
2 min readApr 5, 2017

--

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.

TaskTests

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.

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().

The test: testSetup()

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

From here onwards, the world is your oyster…

The project can be found on github: https://github.com/pardel/tdd-realm-playgrounds

But is it fast?

Oh yes, it’s fast: https://realm.io/news/introducing-realm/#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 below. It covers the subject of this article as well as others.

Thank you!

Big thank you to Marin Todorov for catching a bad error.

If you found this tutorial useful, make sure you check out my upcoming LeanPub book:

Test or GTFO! — a guide to iOS Test Driven Development with Swift”.

--

--

Paul Ardeleanu
Paul Ardeleanu’s Blog

iOS & Web engineer, trainer and coach - with a dash of UX & UI.