Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Essential Groovy DSLs


[ 44 ]

Here is a simple Spock test specification. The specification itself is a Groovy class
extended from the spock.lang.Specification class. It contains one feature method
called "the truth could not be truer" and it has two blocks. The specification itself is
written in the Groovy language, and so far in the book, we have barely touched on
the syntax of the language at all. However, it still should be possible to read this test
specification and understand what it is aiming to achieve.


import spock.lang.Specification

class ChapterThreeSimpleSpec extends Specification {
def "the truth could not be truer" () {
given:
def truth = true

expect:
truth
}
}

Blocks


Spock feature methods comprise of combinations of blocks. In the following
example, we will see how we can specify a BDD style given, when, then sentence.
We have a block for each of the BDD keywords. The string description after each
keyword is entirely optional, but it is best practice to provide it because it adds
readability to your specifications:


void "two wrongs don't make a right" () {
given: "two false statements"
def theWorldIsFlat = false
def theEarthOrbitsTheSun = false

when: "we combine the two falsehoods"
def copernicusWasWrong =
theWorldIsFlat && theEarthOrbitsTheSun

then: "Copernicus was telling the truth"
! copernicusWasWrong
}

http://www.ebook3000.com
Free download pdf