I have setup a small example that demonstrates how to use grails validation on non domain objects using the command pattern.
Collecting all required information was not that easy. Forums do not yet cover many G&G related topics, at least if you want to look under the hood of it

In general, my blogs target G&G developers. You should have at least an idea of how to use it, how to setup a project and what a controller is. My code is tested against Grails 1.1

Short summary

We are going to setup a simple controller with two closures. The one we use is responsible for logging a user into any platform.
Our controller uses a command to gather all params and to validate its values.

The controller

First thing you should create is the controller.
grails create-controller my
You might now copy and paste the following code into your controller class.

grails-app/controllers/MyController.groovy class MyController { def index = { } def run = { MyCommand cmd -> if(cmd.hasErrors()){ render(view:"error") }else{ render(view:"ok") } } } class MyCommand { String login String passwd1 String passwd2 static constraints = { login(blank:false, size:5..15, validator: { it=="foobar" }) passwd1(blank:false, validator: { val, obj -> obj.properties['passwd2']==val }) } }

The important closure for the upcoming test is called “run”.
As an argument it takes a command object.
The springframework behind the scenes is taking care, that all request params are properly mapped to the command object (MyCommand).
Furthermore the command object’s constraints are executed prior any other line of code in the “run” closure.
A powerful feature if you ask me :O)

The command class itself is in charge of all the validation work. As outlined in the grails docs (very good ones indeed) all domain oriented constraints
can be applied to non domain validation objects as well.

The contraint:

login(blank:false, size:5..15, validator: { it=="foobar" })

for example adds an error if the param login is null, if its length is smaller 5 chars or greate 15, or if the validator is returning anything else than null.
Adding an error ?
Grails is making extensive use of spring’s error handling. Have a look at their excellent docs.
For each error, an error object is added to the command object. The controller checks for errors in the command validation and can redirect back to the form if needed.

The test class

test/integration/MyControllerTests.groovy import grails.test.* class MyControllerTests extends ControllerUnitTestCase { protected void setUp() { super.setUp() } protected void tearDown() { super.tearDown() } void testValidCommand() { def cmd = new MyCommand(login:"foobar", passwd1:"password", passwd2:"password") def cntr = new MyController() cntr.run(cmd) assert "ok" == cntr.modelAndView.view } void testInvalidCommand() { def cmd = new MyCommand(login:"foobar", passwd1:"password", passwd2:"not-equals") def cntr = new MyController() cntr.run(cmd) //println cmd.errors.allErrors println "field error " + cmd.errors.fieldError assert 'passwd1' == cmd.errors.getFieldError('passwd1').field assert 'validator.invalid' == cmd.errors.getFieldError('passwd1').code } }

The test itself is simple. You have to create a command object that you use as the request object when calling the “run” closure within the controller.
The way I evaluate an error is ok, but not as good as I wanted it to be.
Grails ships with an enhanced way to handle message codes. Instead of letting the developer create a message key for each error, Grails makes strong usage of their convention over configuration approach by automatically assigning errors to dedicated message keys.
The error key for the login:blank constraint would be mapped in grails-app/i18n/messages.properties as:myCommand.login.blank.
Again the time consuming job of assigning messages keys to errors is omitted.

What I was not yet able to achieve is to fetch the associated error key for a given constraint within a test case.
So, what I am looking for is a line like:

assert 'myCommand.login.blank' == cmd.errors.getField('login').???

Well, I hope that this blog helped you a bit. Yo may leave a comment or try to reach my directly using the steademy plugin and invite me (tmaus@steademy.com) from within the firefox plugin.

Have a nice day

Thorsten

Tags: , ,



Reader's Comments

  1. James | June 26th, 2009 at 4:36 pm

    Thorsten
    I like your article and I was curious about the following

  2. James | June 26th, 2009 at 4:37 pm

    ..sorry.
    1. Can you make your little source code available ?
    2. have you extended this further to actually use commands for manipulating a whole domain for an application…and storing commands in the db for purposes of audit, replaying them to reconstruct your domain model etc.. .?

  3. tmaus | July 10th, 2009 at 12:51 pm

    I was already working on a more complex example to illustrate the command validation.

    As my roots are in the java world, I process any validation within the controller layer. I thus have not yet worked on plain domain validation.
    From my point of view, domain validation has been documented excellently, where as validation on the controller layer using the command pattern is rarely handled.

    I will try to upload my extended example within the next couple of days

  4. Christophe | July 15th, 2009 at 3:05 am

    Did you look also at mockForConstraintsTests, it seems well designed to test command object

    Thanks for your post, he did help me out.

Leave a Comment