Last updated: •Original version:
Apart from being an awesome code prototyping tool, the Xcode Playgrounds can also be used for Test Driven Development (TDD). For a refresher on TDD see this Wikipedia page.
Let’s say we’re designing a struct to represent Todo items:
struct Todo {
}
We’ll add its associated tests (well, one for now):
class TodoTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testTodo() {
XCTAssertNotNil(Todo())
}
}
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.042 (0.044) seconds
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 the guard-rspec gem 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.
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.