How do I specify a Range instead of List in the 'where:' block of a Spock specification
Asked Answered
T

1

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?

Tillich answered 17/1, 2014 at 0:44 Comment(0)
M
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)
}
Marasmus answered 17/1, 2014 at 1:20 Comment(6)
Thanks! Any insights as to why you need the parentheses?Tillich
<< 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 docs.codehaus.org/display/GROOVY/JN2535-ControlBrilliancy
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.Tillich
I often wish .. had a higher precedence, I often get irked by not being able to do 1..2.each { println it }Claim
Here is something similar to your case 1..2.with { it * 2 } :)Marasmus
Do not foget the @Unroll annotation!Triplicity

© 2022 - 2024 — McMap. All rights reserved.