Skip to content

Instantly share code, notes, and snippets.

@jlacar
Last active March 10, 2016 05:45
Show Gist options
  • Save jlacar/33a5c0a691213d7385ad to your computer and use it in GitHub Desktop.
Save jlacar/33a5c0a691213d7385ad to your computer and use it in GitHub Desktop.
Add some syntactic sugar to make Spock sweet!

Use label comments to make Spock specs more conversational

Spock and Geb (pronounced /jeb/), are relatively new Groovy-based frameworks for writing Behavior-Driven Development (BDD) style test specifications. They allow you to write very concise and expressive test code.

The example code below is from gebish.org:

class LoginSpec extends GebSpec {
    def "login to admin section"() {
        given:
        to LoginPage
         
        when:
        loginForm.with {
            username = "admin"
            password = "password"
        }
         
        and:
        loginButton.click()
         
        then:
        at AdminPage
    }
}

While this is pretty concise, it's still a bit too terse and cryptic to anyone unfamiliar with Spock and Geb. However, with some refactoring and creative use of label comments, you can make the spec much more readable and approachable for techies, non-techies, trekkies, and non-trekkies alike.

The comments I added below may look like they're incomplete but when you read them as part of the spec, they really help you glide through the story and grok what the spec is all about.

class AdminLoginSpec extends GebSpec {
    def "Admin user's landing page is the Admin Page"() {
        given: "an admin user goes"
        to LoginPage
    
        when: "he fills in the"
        loginForm.with {
            username = "admin"
            password = "password"
        }
    
        and: "submits the form with a"
        loginButton.click()
    
        then: "the user ends up"
        at AdminPage
    }
}

Sweet, Spock! Now that seems very logical.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment