Wednesday, May 20, 2009

Testing validation parameters using easyb in Grails

If you want to test out domain class constraints, you can use easyb as 
follows: 

My domain class is Subscription.groovy, and it has several 
parameters.  Only one parameter is required: subscriptionCode.  If you 
have any complex data types (such as my LmsTimeZone domain class) you 
need to provide those or the test fails.   When you validate, you can 
check the parameters that failed with the ensure method.  Here's an 
example: 

scenario "Subscription cannot be created without a subscription code", 

        given "A new Subscription",{ 
                subscription = new Subscription() 
        } 
        when "required parameters are supplied except subscriptionCode", { 
                subscription.subscriptionCode = null 
                subscription.activationTimeZone = LmsTimeZone.get(1) 
                subscription.expirationTimeZone = LmsTimeZone.get(1) 
        } 
        then "the subscription validation shows subscriptionCode is not 
supplied", { 
                subscription.validate().shouldBe false 
                ensure(subscription.errors) { 
                        contains "subscriptionCode" 
                } 
                subscription.save(flush:true).shouldBe null 
        } 



I saved this as SubscriptionStory.groovy in my test/behavior package. 
Make sure you use the keyword "Story" or "Behavior" when making your 
test classes or easyb will not pick up your test. 

Hope that helps someone out there, it took me a bit to figure it out!