Jordi Chacón
Jordi Chacón

Reputation: 1737

Declare multiple variables in one line in Spock when: block

I would like to know how I can define, without initializing, multiple variables in one line in Spock spec as shown below.

I have tried:

import spock.lang.Specification

class exampleSpec extends Specification {

  def "foo"() {
    when:
    def a, b
    a = 0
    b = 1

    then:
    a != b
  }
}

But this fails when accessing b: No such property: b for class: ....

I have managed to get the following to work: def (a, b) = []

But I'd like something better.

Any help is greatly appreciated!

I am using:

Groovy Version: 2.4.3 JVM: 1.8.0_45 Vendor: Oracle Corporation OS: Linux

Upvotes: 1

Views: 7000

Answers (2)

ScientificMethod
ScientificMethod

Reputation: 513

You should use the where: block to pass parameters. There's no def required because they're passed as an argument, if you're feeling fancy you can even have a test that is run multiple times.

    def "Use where to pass test data"(){
        expect: 1 == myNumber
                2 == myOther1
        where: myNumber = 1
               myOther1 = 2
    }

Here's a link to some other examples I've written that show how to pass data to your tests. If you really like multiple assignment (even though it's not a good idea) here's how you could use it in a where: block.

If you're curious about the various blocks here is a summary of everything I've read. Don't take my word for it, here's some official documentation.

You might be happy to know that this issue has been raised already, but it hasn't seen any activity in the last month. My assumption is that something about multiple assignment doesn't agree with the AST transformations that Spock uses on your code.

Upvotes: 1

dmahapatro
dmahapatro

Reputation: 50245

I fear that cannot be done in any of the blocks (like given:, setup:, when:). There is an easy work around.

@Grab(group='org.spockframework', module='spock-core', version='0.7-groovy-2.0')

import spock.lang.Specification

class ExampleSpec extends Specification {

  def "foo"() {
        def a, b

        when:
        a = 0
        b = 1

        then:
        a != b
    }
}

Move the declaration out of when:/given:/setup: block and have them as method variables. The setup:/given: label is optional and may be omitted, resulting in an implicit setup block.

Although this works, I would like to know the reason why this did not work otherwise. You can create an issue in github.

Upvotes: 2

Related Questions