Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Essential Groovy DSLs


[ 48 ]

Together these fixtures and helper methods give us a neat way to test the expected
outcome of running an external Groovy script. Remember this one because we will
make use of it in the following chapters of the book:


def "HelloWorld says Hello World"() {
given: "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()
}

Where blocks


The BDD style syntax provided in Spock allows us to write very expressive tests,
but because of its nature can become very repetitive when we have multiple
expectations we want to test, which have the same or different outcomes and
which are data-driven. Spock fortunately has a very useful where: block to
cover this scenario.


The where blocks always come at the end of a feature method. In the following
example, the where block defines two feature method variables, filename and
expectedOutput. The feature method will iterate the values for each of these
variables applying each in turn and asserting the outcomes in turn.


def "HelloWorld says Hello World in Java and Groovy styles"() {
given: "we have a Hello World script"
def script = new File(fileName)
when: "we run the script"
shell.evaluate script
then: "the script outputs the correct details"
expectedOutput == output()
where: "we have different versions of HelloWorld"
fileName | expectedOutput
"scripts/ChapterTwo/Hello.groovy" | "Hello, World!"
"scripts/ChapterTwo/HelloWorld.groovy" | "Hello, World!"
}

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