Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 3

[ 45 ]

For the most part, we can write whatever we like within the block itself. However,
Spock applies some rules, which make sense. The then: and expect: blocks should
only contain expressions that can be evaluated as Boolean expressions. In the next
chapter, we will cover how Groovy's interpretation of truth is wider than Java. In
effect any expression which, evaluates to Boolean true, is a positive or non null value
or a collection with elements in it will all evaluate to true.


As you would expect the code can have multiple lines in any block. However, it may
make sense to logically separate this to aid the readability of a test. For instance,
the previous given: block can be been broken up as follows:


given: "a flat world"
def theWorldIsFlat = false
and: "two celestial bodies"
def theEarthOrbitsTheSun = false

We can extend any block of our test specification with an additional and: block.
Here, we will add a second expect: to the specification:


void "we can extend Spock specs with and blocks" () {
given: "Two Integer numbers"
Number a = 10
Number b = 5

expect: "Integer multiplication and addition are commutative"
a * b == b * a

and:
a + b == b + a
}

Spock does its best to preserve the logical structure of our BDD style specification, so
it will disallow sequences of blocks that don't make sense. Odd block sequences such
as given/then or given/expect/when will either result in a polite suggestion from
Spock to use an alternative or a syntax error.

Free download pdf