Pavel
Pavel

Reputation: 163

How to execute setupSpec() only once for all inheritable classes in Spock

My tests are located in different classes which extended from BaseSpec class that in turn extended from Specification class of Spock Framework.

class BaseSpec extends Specification {
    def setupSpec() {
        println('run setupSpec() from BaseSpec')
    }

    def cleanupSpec() {
        println('run cleanupSpec() from BaseSpec')
    }
}
class FirstTestClass extends BaseSpec {
    def setup() {
        println('run setup() from FirstTestClass')
    }

    def cleanup() {
        println('run cleanup() from FirstTestClass')
    }

    def 'do test1'() {
        given:
        println('run "do test1" from FirstTestClass')
    }
}
class SecondTestClass extends BaseSpec {
    def setup() {
        println('run setup() from SecondTestClass')
    }

    def cleanup() {
        println('run cleanup() from SecondTestClass')
    }

    def 'do test2'() {
        given:
        println('run "do test2()" from SecondTestClass')
    }
}

As expected setupSpec() and cleanupSpec() are executed for each inheritable class.

run setupSpec() from BaseSpec
run setup() from FirstTestClass
run "do test1" from FirstTestClass
run cleanup() from FirstTestClass
run cleanupSpec() from BaseSpec

run setupSpec() from BaseSpec
run setup() from SecondTestClass
run "do test2()" from SecondTestClass
run cleanup() from SecondTestClass
run cleanupSpec() from BaseSpec

Is there a way execute setupSpec() and cleanupSpec() only once? Or I can only put all feature methods in one class?

Thanks!

Upvotes: 7

Views: 6780

Answers (2)

NATHAN
NATHAN

Reputation: 11

If you only want to run setupSpec once, you can do something like this in your BaseSpec class:

static INITIALIZED_BASESPEC = false

def setupSpec() {
    if (!INITIALIZED_BASESPEC) {

        //Do setup stuff
        
        INITIALIZED_BASESPEC = true
    }
}

Upvotes: 1

kriegaex
kriegaex

Reputation: 67417

I don't think you should do that, I agree on that with Tim. But if you insist, you can do something at the very beginning/end of Spock execution if you implement a global extension:

Just use the start() and stop() methods. You could also keep global state and use visitSpec(SpecInfo) to do what you want just for a certain group of tests - whatever your creativity comes up with.

Let me know if this pointer leaves you with follow-up questions.

Upvotes: 1

Related Questions