13 May 2012

Grails, Spock & IntelliJ Idea First Steps

I've been meaning to spend some time setting up a Test Driven Development approach to my Grails development and after looking at the options, Spock seems to be a popular and capable testing and specification framework for Grails and Java development.

I'm using Grails 2.0.1, the Grails Spock plugin and IntelliJ IDEA 10.5. I'm going to pick an existing Grails project add Spock and write a simple unit test for one of my domain classes. This grails-spock-example project was one of the most helpful posts I ran across.
 The first step is to select an existing Grails project and install the Spock plugin.

$ grails install-plugin spock

I'm going to create a Spock unit test for a User domain class and I'll put the specification in the file ~/Grails/<project>/test/unit/<package-path>/domain/UserSpec.groovy. Here's what the file looks like before we've written the first specification

package com.MyApp.domain

import grails.plugin.spock.UnitSpec
import com.MyApp.User

class UserSpec extends UnitSpec {
}

Here's a simple test that creates a user and confirms that the findByEmail call works

class UserSpec extends UnitSpec {
    def "find user by email"() {
        setup:
        mockDomain(User)

        when:
        new User(email: "test@gmail.com", password: "xyz", createDate: new Date(), modifyDate: new Date()).save()

        then:
        User.findByEmail("test@gmail.com") != null
        User.findByEmail("bogusemail") == null
    }

To run all of my Spock tests, execute this command:

$ grails test-app :spock

Some examples of the test-app option can be found in the Grails documentation. To run only the Spock unit tests you would use these options:

$ grails test-app unit:spock

Here are some of the Spock example specifications I found useful:

- SpockBasics page from the Spock wiki
- grails-spock-examples and overview
- Discussion of Mocking in Groovy
- Setup of Spock and IntelliJ
- Screencast and blog posting on Spock and IntelliJ


Tags:
0 comments