October 2, 2017

Spocklight: Reuse Variables In Data Providers

Writing a parameterized specification in Spock is easy. We need to add the where: block and use data providers to specify different values. For each set of values from the data providers our specifications is run, so we can test for example very effectively multiple input arguments for a method and the expected outcome. A data provider can be anything that implements the Iterable interface. Spock also adds support for a data table. In the data table we define columns for each variable and in the rows values for each variable. Since Spock 1.1 we can reuse the value of the variables inside the data provider or data table. The value of the variable can only be reused in variables that are defined after the variable we want to reuse is defined.

In the following example we have two feature methods, one uses a data provider and one a data table. The variable sentence is defined after the variable search, so we can use the search variable value in the definition of the sentence variable.

package mrhaki

import spock.lang.Specification
import spock.lang.Unroll

class CountOccurrencesSpec extends Specification {

    @Unroll('#sentence should have #count occurrences of #search (using data table)')
    void 'count occurrences of text using data table'() {
        expect:
        sentence.count(search) == count

        where:
        search  | sentence                                                  || count
        'ABC'   | "A simple $search"                                        || 1
        'Spock' | "Don't confuse $search framework, with the other $search" || 2
    }

    @Unroll('#sentence should have #count occurrences of #search (using data provider)')
    void 'count occurrences of text using data provider'() {
        expect:
        sentence.count(search) == count

        where:
        search << ['ABC', 'Spock']
        sentence << ["A simple $search", "Don't confuse $search framework, with the other $search"]
        count << [1, 2]
    }
}

When we run the specification the feature methods will pass and in we see in the @Unroll descriptions that the sentence variable uses the value of search:

Written with Spock 1.1-groovy-2.4.