Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 3

[ 49 ]

Fixture blocks


Sometimes, we will have fixture data which is specific to a feature method and is not
something we want to be shared across multiple feature methods. Spock provides
setup: and cleanup: for this purpose.


def "Fixtures can be in blocks too"() {
setup:
orig = System.out
out = new ByteArrayOutputStream()
System.setOut(new PrintStream(out))
binding = new Binding()
shell = new GroovyShell(binding)
and: "we have a Hello World script"
def script = new
File("scripts/ChapterTwo/Hello.groovy")
when: "we run the script"
shell.evaluate script
then: "the script outputs the correct details"
"Hello, World!" == output()
cleanup:
System.setOut(orig)
}

Note that the setup: block is synonymous with given: and can often be
used interchangeably.


Testing Gradle using Spock


We started out the chapter by describing some of the features of Gradle. If we
take test-driven development (TDD) seriously, it should be possible to assert any
expected outcome using a test tool. As it happens, it is not difficult to use Spock to
verify the assertions we made earlier about how Gradle itself works. Consider the
following feature method:


def "hello task says Hello, World!"() {
given: "we have a gradle build command"
def command = "gradle -q -b hello.gradle hello"
when: "we run the build command"
def proc = command.execute()
proc.waitFor()
then: "the script outputs the correct details"
"Hello, World!" == proc.in.text.trim()
}
Free download pdf