Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's good style for preconditions in Spock feature methods?

Tags:

spock

In a feature method, one specifies the feature action in a when: block, the result of which gets tested in a subsequent then: block. Often preparation is needed, which is done in a given: clause (or setup: or fixture method). It is equally useful to include preconditions: these are conditions which are not the subject of the feature test (thus should not be in a when:-then: or expect:) but they assert/document necessary conditions for the test to be meaningful. See for example the dummy spec below:

import spock.lang.*

class DummySpec extends Specification {
  def "The leading three-caracter substring can be extracted from a string"() {
    given: "A string which is at least three characters long"
    def testString = "Hello, World"

    assert testString.size() > 2

    when: "Applying the appropriate [0..2] operation"
    def result = testString[0..2]

    then: "The result is three characters long"
    result.size() == 3
  }
}

What is the suggested practice for these preconditions? I used assert in the example but many frown upon asserts in a Spec.

like image 538
Tamás Avatar asked Nov 13 '14 09:11

Tamás


1 Answers

I've been always using expect for such scenarios:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class DummySpec extends Specification {
  def "The leading three-caracter substring can be extracted from a string"() {
    given: "A string which is at least three characters long"
    def testString = "Hello, World"

    expect: "Input should have at least 3 characters"
    testString.size() > 3

    when: "Applying the appropriate [0..2] operation"
    def result = testString[0..2]

    then: "The result is three characters long"
    result.size() == 3
  }
}
like image 144
Opal Avatar answered Jan 04 '23 13:01

Opal