Marcin Erdmann

Groovy, Grails, Geb...

Built in way of mocking g.render() in Grails 2

In my previous post I've came up with a way of mocking g.render() tag in Grails 2 unit tests. As Rob Fletcher has pointed out to me there is a much simpler, built in way of doing that.

Looks like I haven't paid enough attention while looking at ControllerUnitTestMixin, a superclass of GroovyPageUnitTestMixin which is being applied to your taglib tests when marking them with @TestFor. Apparently there is a views field that allows you to specify templates without using the file system. Using that field the test for the handlebars template rendering taglib from the earlier post becomes much simpler:

class HandlebarsTagLibSpec extends Specification {

    def 'jsTemplate renders script tag with template'() {
        def templateName = 'someTemplate'
        views["/handlebars/_${templateName}.gsp"] = '<div>template content</div>'

        String rendered = applyTemplate("<handlebars:template name=\"${templateName}\" />")
        GPathResult result = new XmlSlurper().parseText(rendered)

        then: == 'script'
        result.@type == HANDLEBARS_TAGLIB_MEDIA_TYPE
        result.@id == templateName
        result.div.text() == 'template content'

    def 'exception is thrown when js template is not found'() {
        def templateName = 'doesNotExist'

        applyTemplate("<handlebars:template name=\"${templateName}\" />")

        GrailsTagException exception = thrown()
        exception.message.startsWith("Template not found for name [/handlebars/${templateName}]")