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?
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/