Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 3

[ 47 ]

Here is a slightly complex but very useful example of a use for fixture methods.
We will go into more detail in later chapters about how to use the GroovyShell
class. In this example, we will set up a Groovy shell in our test specification and a
PrintStream object to capture the output from the shell. The GroovyShell class will
allow us to execute Groovy source code from a file in our path without the need to
compile it and include it in the class path:


GroovyShell shell
Binding binding
PrintStream orig
ByteArrayOutputStream out

def setup() {
orig = System.out
out = new ByteArrayOutputStream()
System.setOut(new PrintStream(out))
binding = new Binding()
shell = new GroovyShell(binding)
}
def cleanup() {
System.setOut(orig)
}

Helper methods


A feature method is any method that has a Spock block in it. Any method that does
not have a Spock block defined, and is not one of the four fixture methods, will be
treated by Spock as a helper method and will be compiled into the test as a regular
instance method.


We can call a helper method from anywhere in one of our feature methods. For
instance, the following helper method works alongside our GroovyShell fixture
methods to return the output after executing a Groovy script in the Groovy shell:


protected String output() {
out.toString().trim()
}
Free download pdf