Chapter 10. Extending Spock

Although Spock has a great selection of built-in features, it’s always useful to have extensibility. In this chapter, we look at various ways by which you can extend the default capabilities of your Spock specifications. We’ll look at composing assertions with Hamcrest matchers, providing reusable functionality with JUnit rules and Spock’s own extension mechanism.

The Message Timeline

We’ll refer back a couple of times in this chapter to a TimelineSpec specification class that tests the database queries and object marshalling around retrieving a user’s timeline. We saw some variation on this earlier in the book, but let’s just revisit it quickly here:

class TimelineSpec extends Specification {

  def dataSource = new JdbcDataSource(
    url: "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false"

  DBI dbi = new DBI(dataSource)
  @AutoCleanup Handle handle

  UserStore userStore
  MessageStore messageStore
  FollowingStore followingStore

  @Subject User user
  User followedUser
  User otherUser

  def setup() {
    dbi.registerArgumentFactory(new TimeTypesArgumentFactory())
    dbi.registerMapper(new TimeTypesMapperFactory())

    // tag::fixtures[]
    handle =

    userStore = handle.attach(UserStore)

    messageStore = handle.attach(MessageStore)

    followingStore = handle.attach(FollowingStore)

    user = userStore.insert("khan")
    followedUser = userStore.insert("kirk")

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.