-
-
Save ntung/da7b5075a57849b52191c23d7fa28d4b to your computer and use it in GitHub Desktop.
Grails + Spock: Testing Rendering views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hi ${text}! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserController { | |
def index(final String username) { | |
flash.errors = "ops!" | |
render view: "index", model: [username:username, text:username] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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