Issue with spock and grails 2.0.1 when testing controller

Go To StackoverFlow.com

1

While running Spock controller test:

import grails.plugin.spock.* import grails.test.mixin.*

@Mock(MusicItem) class MusicItemControllerSpec extends ControllerSpec {

def "Creating element with correct parameters"() {
    setup:
    controller.params.artist = "John Lennon"
    controller.params.name = "Imagine"
    controller.params.location = new URL ("http://localhost")

    when:
    controller.save()

    then:
    redirectArgs.action == "show"
    controller.flash.message != null
    MusicItem.count() == 1
}

}

Where part that is tested is:

def save() {
    def musicItemInstance = new MusicItem(params)
    if (!musicItemInstance.save(flush: true)) {
        render(view: "create", model: [musicItemInstance: musicItemInstance])
        return
    }

    flash.message = message(code: 'default.created.message', args: [message(code: 'musicItem.label', default: 'MusicItem'), musicItemInstance.id])
    redirect(action: "show", id: musicItemInstance.id)
}

That is part of controller. I'm getting this exception:

| Running 6 spock tests... 3 of 6 | Failure: Creating element with correct parameters(myvibe.fondation.MusicItemControllerSpec) | java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? at myvibe.fondation.MusicItemController.save(MusicItemController.groovy:29) at myvibe.fondation.MusicItemControllerSpec.Creating element with correct parameters(MusicItemControllerSpec.groovy:39) | Running 6 spock tests... 4 of 6

When I remove this line from save() method:

        flash.message = message(code: 'default.created.message', args: [message(code: 'musicItem.label', default: 'MusicItem'), musicItemInstance.id])

Than all work fine. What I'm missing?

2012-04-05 20:26
by robert
Is the test spec in. integration or unit test? ControllerSpec is for Unit test, and is afaik not needed in 2.0.x In integration I extend IntegrationSpe - sbglasius 2012-04-06 05:49
It is in unit spec - robert 2012-04-06 18:49


3

It's failing because of message tag. Following should work

setup:
controller.metaClass.message = {args -> "mockMessage"}

http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/

2012-04-06 20:47
by Saurabh
yes. that does it. thanks - robert 2012-04-08 18:30
Cool...Please don't forget to accept the answer if that works..thank - Saurabh 2012-04-08 18:31
Ads