Mike Sallese Mike Sallese - 2 months ago 8
Groovy Question

Is it possible to use a list defined in a given block in a where block in spock?

For example:

given: "a list and a variable"
def checkThese = someStaticFunctionThatReturnsAList()
a = 5

expect: "a is greater than b"
a > b

where: "B is a list defined in given"
b << checkThese
//b << [1,2,3,4,5] will work, the above will not


This will fail and say there is no such property checkThese. How can I accomplish this?

Answer

It does not work, because the where: block although written last in the spec method is actually executed first, since it is used for "data driven testing". It actually facilitates calling your method several times (for each data iteration that you set up there).

So in your case:

given: "a list and a variable"
def checkThese = someStaticFunctionThatReturnsAList() // this line will actually get executed every time your spec method runs
a = 5

expect: "a is greater than b"
a > b

where: "B is a list defined in given"
b << checkThese // will not work (because the given block is not executed yet and the variable is not created yet and not accessible
b << [1,2,3,4,5] // works because you're setting up the data explicitly
b << someStaticFunctionThatReturnsAList() // will also work 
Comments