12

The following example code:

class MySpec extends spock.lang.Specification {
    def "My test"(int b) {
        given:
        def a = 1

        expect:
        b > a

        where:
        b << 2..4
    }
}

throws the following compilation error: "where-blocks may only contain parameterizations (e.g. 'salary << [1000, 5000, 9000]; salaryk = salary / 1000')"

but using a List instead of a Range:

        where:
        b << [2,3,4]

compiles and runs fine as expected.

Could I also specify a Range somehow?

AndrewW
  • 678
  • 6
  • 18

1 Answers1

14

Use

where:
b << (2..4)

The test can be optimized as below as well. Note no arguments to the test.

def "My test"() {
  expect:
  b > a

  where:
  a = 1
  b << (2..4)
}
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • 1
    Thanks! Any insights as to why you need the parentheses? – AndrewW Jan 17 '14 at 06:31
  • 5
    << has a higher precedence than .., so b << 2..4 is interpreted as (b << 2)..4. This fails because 2 is not an iterable, before failing due to .. See http://docs.codehaus.org/display/GROOVY/JN2535-Control – Luis Muñiz Jan 17 '14 at 09:47
  • 1
    Thanks for the link and explanation. In the docs they're on the same line (<< >> >>> .. ..<). Does this mean they have the same precedence and are therefore interpreted in order left to right, leading to the failure? This also makes sense to me. – AndrewW Jan 17 '14 at 10:43
  • 1
    I often wish `..` had a higher precedence, I often get irked by not being able to do `1..2.each { println it }` – tim_yates Jan 17 '14 at 15:23
  • Here is something similar to your case `1..2.with { it * 2 }` :) – dmahapatro Jan 17 '14 at 15:48
  • Do not foget the @Unroll annotation! – nicoabie Mar 09 '21 at 20:53