Unit testing Grails controllers with duplicate form submission check functionality

I’ve been doing some Grail 2.0.1 development recently. I like the maturity of framework and the ease of doing things.

One of the things Grails comes with is a simple way of avoiding duplicate form submission. Have a look at the code bellow:

def myControllerMethod(){
    render “theGoodStuff”
  } .invalidToken {
    render “theBadStuff”

That’s the controller bit. In your view you need to enable use of that feature by passing useToken parameter to form tag:

<g:form action=”myControllerMethod” useToken=”true”></g:form>

It looks very simple and elegant. However when we would like to test the controller we need to make sure we match the token when calling the method.

Documentation on testing Grails application and this particular functionality contains the way of doing so, however I found it not working with Grails 2.0.1.  Not much was blogged about it so I looked through the mailing lists. I found one trail and a bug report for this issue.

Anyway, to make it work, the piece of documentation from Grails, version 1.4.x explains how to do it, and it works.

In controller test method we need to place this code:

def token = SynchronizerTokensHolder.store(session)
params[SynchronizerTokensHolder.TOKEN_URI] = '/myController/myControllerMethod’
params[SynchronizerTokensHolder.TOKEN_KEY] = token.generateToken(params[SynchronizerTokensHolder.TOKEN_URI])


Happy testing. Greg

Useful links: