Recently, I had to write the Integration test cases for a controller and I had extended my test Spec with IntegrationSpec. While writing the test case for action that renders a template with model I came to know that there’s no straight and simple way to test it. For example, action looked like:
class UserController { static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"] def list = { render(template: 'list', model: [userInstanceList:User.list(params)]) } // more actions }
Now, in order to test it, we need to add the following code to the setup method:
UserController.metaClass.render = { Map map -> renderedMap = map }
so that the overall test script for the controller looks like:
class UserControllerSpec extends IntegrationSpec{ UserController controller Map renderedMap public void setup() { controller = new UserController() UserController.metaClass.render = { Map map -> renderedMap = map } } public void cleanup() { } void "test list"(){ when: controller.list() then: renderedMap renderedMap.template renderedMap.template.equals('list') renderedMap.model renderedMap.model.userInstanceList.size() > 0 } }
Now, you will be able to get the name of the rendered template with renderedMap.template and the model with renderedMap.model. If your test case renders a view then the view name would be available with renderedMap.view.
You can see the whole working code/application here.
Recent Comments