Chapter 7. Idiomatic Spock

So far, we’ve looked at the mechanics of how to write specifications with Spock as well as all the core functionality. If you’ve read this far and followed along with the examples, you basically know how to write specifications.

However, it’s easy to take Spock and write very verbose, Java-like, JUnit-like specifications that don’t really get the best out of what Spock or Groovy have to offer. There’s more to Spock than just the given, when, then structure and implicit assertions.

In this chapter, I want to explore a range of smaller topics that serve as tips on writing idiomatic Spock specifications. By “idiomatic,” I mean that test code seamlessly uses the features and grammar of Spock and Groovy.

Let’s begin at the highest level by looking at how to structure a suite of specification classes.

Organizing Tests

Many IDEs and frameworks will automatically generate stub test classes for you. For example, IntelliJ IDEA can generate a skeleton Spock specification based on a class. It can even generate a feature method for each public method in the class.

Perhaps because such tools encourage them down this path, many developers seem to become stuck in a rut in which each production class has a one-to-one correspondence with a test class. This doesn’t need to be the case.

It’s a perfectly acceptable way to begin, but there are many valid reasons why strictly maintaining a one-to-one relationship between production classes and test classes is a bad idea. ...

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.