Built in way of mocking g.render() in Grails 2
Posted on 12 July, 2012 (1 decade ago)
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:
@TestFor(HandlebarsTagLib)
class HandlebarsTagLibSpec extends Specification {
def 'jsTemplate renders script tag with template'() {
given:
def templateName = 'someTemplate'
views["/handlebars/_${templateName}.gsp"] = '<div>template content</div>'
when:
String rendered = applyTemplate("<handlebars:template name=\"${templateName}\" />")
GPathResult result = new XmlSlurper().parseText(rendered)
then:
result.name() == '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'() {
given:
def templateName = 'doesNotExist'
when:
applyTemplate("<handlebars:template name=\"${templateName}\" />")
then:
GrailsTagException exception = thrown()
exception.message.startsWith("Template not found for name [/handlebars/${templateName}]")
}
}