Spocklight: Only Run Specs Based On Conditions
In a previous blog post we have seen the IgnoreIf
extension. There is also a counterpart: the Requires
extension. If we apply this extension to a feature method or specification class than the method or whole class is executed when the condition for the @Requires
annotation is true. If the condition is false the method or specification is not executed. As a value for the @Requires
annotation we must specify a closure. In the closure Spock adds some properties we can use for our conditions:
jvm
can be used to check a Java version or compatibility.sys
returns the Java system properties.env
used to access environment variables.os
can be used to check for operating system names.javaVersion
has the Java version asBigDecimal
, eg. 1.8.
In the following example we use the @Requires
annotation with different conditions:
package com.mrhaki.spock
import spock.lang.Requires
import spock.lang.Specification
class RequiresSampleSpec extends Specification {
@Requires({ Boolean.valueOf(sys['spock.longRunning']) })
def "run spec if Java system property 'spock.longRunning' is true"() {
expect:
true
}
@Requires({ Boolean.valueOf(env['SPOCK_LONG_RUNNING']) })
def "run spec if environment variable 'SPOCK_LONG_RUNNING' is true"() {
expect:
true
}
@Requires({ javaVersion >= 1.7 })
def "run spec if run in Java 1.7 or higher"() {
expect:
true
}
@Requires({ jvm.isJava8() })
def "run spec if run in Java 1.8"() {
expect:
true
}
@Requires({ os.isWindows() })
def "run only if run on windows operating system"() {
expect:
true
}
}
If we have the same condition to be applied for all feature methods in a specification we can use the @Requires
annotation at the class level:
package com.mrhaki.spock
import spock.lang.Requires
import spock.lang.Specification
@Requires({ jvm.isJava7Compatible() })
class RequiresSpec extends Specification {
def "all feature methods run only if JVM is Java 7 compatible"() {
expect:
true
}
}
Written with Spock 1.0-groovy-2.4.