TDD in Xcode Playgrounds
For updated instructions (Swift 5 and Xcode 11), please visit: https://www.pardel.dev/blog/tdd-in-xcode-playgrounds
Apart from being an awesome code prototyping tool, the Xcode Playgrounds can also be used for Test Driven Development.
For a refresher on TDD see this Wikipedia page: https://en.wikipedia.org/wiki/Test-driven_development
Let’s say we’re designing a struct to represent Todo items:
We’ll add its associated tests (well, one for now):
In a typical workflow, you will have to prop up an entire project (with a test target) to simply run this tests.
Here is an faster alternative — everything in a playground:
The “magic sauce” here is the creation of a test suite for the XCTestCase subclass and running it.
TodoTests.defaultTestSuite().run()
The output will show in the Debug area:
Executed 1 test, with 0 failures (0 unexpected) in 0.006 (0.008) seconds
Magic!
The biggest advantage of this solution is the playground (re)running all your tests every time something changes shortening the feedback look drastically!
This is similar to how guard-rspec works in the Ruby world.
Obviously, this solution can be extended by moving the struct and tests in separate files and only trigger them from the playground page. Those source files can then be shared with the Xcode project to avoid duplication or having to move the code across.
Teaching tool
This method is an awesome teaching technique — I’ve used it with great success recently!
By having tools that shorten the feedback loop, developers will actually seek to write tests as they’ll learn new APIs and design patterns.