Groovy & Grails: Testing and Deploying
Testing Is Built In
Grails generates a test for every domain class, controller, and service you create. You can write unit tests that run fast without a database, integration tests that include the full application context, and functional tests that drive the real server with an HTTP client.
A Unit Test in Spock
Tests are written in Spock, a Groovy testing framework that reads like plain sentences.
class BookSpec extends Specification {
def "title cannot be blank"() {
given:
def book = new Book(title: "")
expect:
!book.validate()
}
}The method name is a sentence, and the blocks given, expect, and when organize the test. Here an empty title fails validation, so the test passes.
Running the Suite
grails test
grails test-appRun the suite often. Compilation errors and test failures are far cheaper to fix now than after deploy.
Packaging for Production
A production Grails app ships as a runnable archive. Grails builds one with a single command.
grails warThe result is a war file in the build folder. A war contains the compiled application and all its dependencies, ready for any servlet container such as Tomcat.
Deploying
Deployment options include dropping the war into a servlet container, running it as a standalone jar, or pushing it to a cloud platform. In production, set the data source to a real database, use environment-specific configuration, and never expose the development console.
- Use SSL and keep secrets in environment variables.
- Set the external database credentials in the production config.
- Run tests in a build pipeline before every release.
- Watch memory and logs, since Grails apps default to a larger heap.
With a green test suite and a war artifact, you are free to deploy wherever the JVM runs.
Key Points
- Grails scaffolds unit, integration, and functional test skeletons.
- Spock specs read like sentences and organize with given, when, and expect.
- grails war packages the application for any servlet container.
- Production config must use a real data source and secure secrets.