Friday 23 December 2011

Unit testing Grails 2.0 Controllers withForm to handle duplicate submits

The documentation is a bit out of date for Grails 2.0.0 for testing controllers with the withForm { } closure to stop double submits.
New in Grails 2.0.0 is that it is more strict with its unit testing when using the withForm method
Add the following in to allow the form token to allow your method to get into the withForm{} block of your code
setup(){ 
    def serverUrl = "http://localhost:80"
    org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerTokensHolder 
    tokenHolder = SynchronizerTokensHolder.store(session)
    def token = tokenHolder.generateToken(serverUrl)
    params[SynchronizerTokensHolder.TOKEN_KEY] = token
    params[SynchronizerTokensHolder.TOKEN_URI] = serverUrl
}