dusty
dusty

Reputation: 189

How to mock render in (Spock, Grails) unit testing Taglib?

I have a simple Tag in my custom Taglib in Grails like this:

def Bar = {attrs, body ->
      Bar bar = Bar.get(attrs.id)
      out << render(template: '/bar', plugin: 'web-core', model: bar)
  }

I need to run unit test ...

But I'd like to use mock render - RenderTagLib or GroovyPagesTemplateRenederer to check the right model and name of template is given instead of using

when:
String string = applyTemplate <foo:bar id="1" />
then:
string.contains('Bar 1')

For example: I have tried to mock GroovyPagesTemplateRenderer like this:

setup:

def mock = Mock (GroovyPagesTemplateRenderer) {

        render(_,_,_,_,_) >> //something 
    }

but render is void method as well as makeTemplate so I have no idea how to do it?

Or what is the best way to unit test Taglib?

If I will change the view of Taglib, output may be different. So I will have to change both unit test (view, tagLib).

This is, why I need to do test Taglib class separately as well as view.

Thank you for your answers ...

Upvotes: 3

Views: 1521

Answers (1)

Martin Hauner
Martin Hauner

Reputation: 1733

You can check the parameters by replacing the render() method via groovy meta programming.

@TestFor(RenderTagLib)
@Mock(Bar)
class RenderTagLibSpec extends Specification {
    Map render
    Bar bar

    def setup() {
        bar = new Bar ()
        bar.save (failOnError: true)

        tagLib.metaClass.render = { Map attrs ->
            render = attrs
        }
    }

    void "bar() passes the correct parameters to render()"() {
        when:
        tagLib.bar (id:bar.id)

        then:
        render.template == '/bar'
        render.plugin == 'web-core'
        render.model == bar
    }
}

Upvotes: 4

Related Questions