Chapter 11. Test-Driven Development: The Diamond Kata

The Diamond Kata is a well-known test-driven development (TDD) exercise. In this chapter, we work our way to a solution demonstrating the use of Spock in a TDD workflow.

As we work through the exercise, we’ll always implement a test before implementing the code that makes it pass. Thus, until we have implemented tests for every condition and made them pass, we will have an incomplete solution—but with each test, it will inch closer to completeness. As we add tests, we’ll see how we can simplify what we need to assert at each step because of the conditions in place.

The Diamond Kata

In case you haven’t come across the Diamond Kata prior to this, let’s review what is involved. The aim is to create a function that accepts a single character as input and returns a matrix of characters in a specific pattern. The matrix should be a perfect square whose dimensions depend on the input character. Starting at A, each row in the pattern uses the next letter of the alphabet up to the argument character and then back down to A. The letters in the matrix form a diamond. The first row should include A, vertically centered surrounded by padding. The second row should include two B characters in the center, separated by a single padding character.

Here are some examples of the pattern:

-A-
B-B
-A-
---A---
--B-B--
-C---C-
D-----D
-C---C-
--B-B--
---A---

The simplest form is the diamond of A.

A

As you can see, all diamonds exhibit vertical and ...

Get Spock: Up and Running now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.