Skip to content

Instantly share code, notes, and snippets.

@ntung
Forked from roalcantara/UserController.groovy
Created July 2, 2019 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntung/da7b5075a57849b52191c23d7fa28d4b to your computer and use it in GitHub Desktop.
Save ntung/da7b5075a57849b52191c23d7fa28d4b to your computer and use it in GitHub Desktop.
Grails + Spock: Testing Rendering views
Hi ${text}!
class UserController {
def index(final String username) {
flash.errors = "ops!"
render view: "index", model: [username:username, text:username]
}
}
import grails.test.mixin.TestMixin
import spock.lang.Specification
import grails.test.mixin.web.GroovyPageUnitTestMixin
//@TestFor is replaced with the Mixin in the test
@TestMixin(GroovyPageUnitTestMixin)
class UserControllerSpec extends Specification {
def controller
def setup(){
//The controller has to be mocked using testFor()
controller = testFor(UserController)
}
void "test something"() {
when:
controller.index(username)
then:
flash.errors
view == "/user/index"
model.username == username
and:
//Method provided by mixin which mimics render method in controller.
//Make sure model is also passed in the map arg
render(view: "/user/index", model: model) == expectedOutput
//or render(template: '/user/_template_name', model: model)
where:
username || expectedOutput
'goku' || "Hi 'goku'!"
'gohan' || "Hi 'gohan'!"
'kuririn' || "Hi 'kuririn'!"
}
}
//reference: http://stackoverflow.com/a/23123835/1603694
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment