Search code examples
unit-testinggrailsgrails-2.0grails-controller

Unit test controller by calling multiple actions


I have a very similar problem to the one described in this question. (The main difference being that i am using Grails 2.1).

Basically i want to write a unit test which does sth like:

// set params so i can create an obj.
def results = controller.save()

// validate results or model/view
results = controller.edit(id, version)

However, this doesn't work, because the first method action (save) has triggered a redirect and the second one would too, which leads to a CannotRedirectException. With the message:

Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.

The proposed solution for this (found in various places) is:

redirectArgs.clear()

However, this doesn't work, because since Grails 2, redirectArgs doesn't exist, there is only

response.redirectUr

which can only be read, not written to.

I have also already tried these things (in various combinations):

response.reset()
clearGrailsWebRequest()
bindGrailsWebRequest()
cleanupGrailsWeb()
controller.redirect([:])
controller.redirect(null)
controller = new OfferObjectController()
controller = mockController(OfferObjectController)

All without any luck.

I have totally run out of ideas what else could work/help. Any suggestion is appreciated!

==== EDIT ====

i forgot to clarify that

response.reset()

kind of works, it lets me call another action, however it seems to undo/rollback the changes done by the previous action, which is exactly what i want to avoid (if i wanted that, i would put the call into its own test[method]).


Solution

  • The answer is

    response.reset()
    

    I don't know why you're receiving that exception. By the way, you should create one task one test.

    I guess you can try this:

    import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
    .....
    
    // set params so i can create an obj.
    def results = controller.save()
    
    def lastRequest = GrailsWebRequest.lookup().currentRequest
    lastRequest.removeAttribute("org.codehaus.groovy.grails.REDIRECT_ISSUED")
    
    // validate results or model/view
    results = controller.edit(id, version)