When your controller returns a model you can simply test the return type.
Given:
def show = {
def bookInstance= Book.get( params.id )
return [ bookInstance: bookInstance] }
}
You test it by:
def model = myController.show()
assertNotNull model.bookInstance
or some such.
If you use the render method in your controller then you would use the ModelAndView object in your controller.
Given:
def save = {
def bookInstance = Book.get(params.id)
render(view:'create',model: [ bookInstance : bookInstance ])
}
You can test it as follows:
bookController.save()
assertNotNull bookController.modelAndView.model.bookInstance
There is one nasty caveat to the render method, and that is if you are rendering a template instead of a view. This is common when you are doing AJAX type calls that only return a partial page. The problem is that Grails will not populate the modelAndView map at all. Nor does render provide a return type.
The answer came from the following mailing list posting:
http://www.nabble.com/Testing-Controller-with-render(template:....)-td18757149.html
Essentially you need to alter the behavior of the render method. You can do this in the setup as follows:
def renderMap
protected void setUp() {
super.setUp()
BookController.metaClass.render = { Map map ->
renderMap = map
}
}
Then Given:
def bookSummary = {
def bookInstance = Book.get(params.id)
render(template: "bookSummary", model: [ bookInstance : bookInstance ])
}
And then you test your model values as follows:
bookController.bookSummary()
assertNotNull renderMap.model.bookInstance
I hope this is helpful.
Happy Grailing!