<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>Music, software, life… and stuff.</description><title>LD.</title><generator>Tumblr (3.0; @ldaley)</generator><link>http://ldaley.com/</link><item><title>Gr8Conf EU, now with more me</title><description>&lt;p&gt;I&amp;#8217;m excited to be presenting a &lt;a href="http://gr8conf.eu/"&gt;GR8Conf EU&lt;/a&gt; this year. This will be my first time at GR8 Conf and I&amp;#8217;m looking forward to meeting some of the Groovy community that I&amp;#8217;ve not had the opportunity to meet before.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ll be &lt;a href="http://gr8conf.eu/Presentations/Testing-with-Geb"&gt;presenting on Geb&lt;/a&gt;, as both an introduction for the uninitiated and to discuss the new features that have appeared in the last few months. It will be an interesting change to present this material to a crowd already comfortable with Groovy; quite different to my upcoming session at &lt;a href="http://www.seleniumconf.org/" title="Selenium Conference 2012 | The future of testing."&gt;SeleniumConf&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Of course, I&amp;#8217;ll also be there representing Gradleware and helping &lt;a href="http://gr8conf.eu/Speakers/Peter-Niederwieser" title="GR8Conf Europe 2012 - Peter Niederwieser"&gt;Peter&lt;/a&gt; give a 3 hour &lt;a href="http://gr8conf.eu/Presentations/Gradle-Bootcamp" title="GR8Conf Europe 2012 - Gradle Bootcamp (*)"&gt;Gradle Bootcamp&lt;/a&gt; that will get anybody up and running with Gradle. I&amp;#8217;ll also be doing another (new) &lt;a href="http://gr8conf.eu/Presentations/To-be-announced" title="GR8Conf Europe 2012 - Releasing software with Gradle"&gt;Gradle session on releasing software&lt;/a&gt;. This will be a tutorial style presentation that will arm you with everything you need to build, test and release open source software to Maven Central with Gradle. There will also be a dive into the Spock and Geb builds to look at how they managing building and testing Grails plugins as part of their builds and automating their release.&lt;/p&gt;

&lt;p&gt;Hope to see you there!&lt;/p&gt;</description><link>http://ldaley.com/post/20402308654</link><guid>http://ldaley.com/post/20402308654</guid><pubDate>Tue, 03 Apr 2012 20:17:58 +1000</pubDate><category>software</category><category>groovy</category><category>conference</category></item><item><title>In response to Rob's post on functional testing.</title><description>&lt;p&gt;Rob, a Geb committer and all around cool dude, recently posted &lt;a href="http://adhockery.blogspot.com/2011/11/fear-loathing-in-functional-testing.html"&gt;some thoughts on function testing&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following is what I intended to be a comment on Rob&amp;#8217;s blog, but it became too long so I decided to post it here. You&amp;#8217;ll notice that the language is a bit weird as in some places I am addressing Rob directly. It should make sense (no guarantees) if you pretend you are reading it as a comment on Rob&amp;#8217;s blog.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This is not a flame war&lt;/strong&gt;, though that would be fun. Rob&amp;#8217;s a friend of mine and a respected colleague. This is just a discussion and exchange of ideas.&lt;/p&gt;

&lt;p&gt;Without further ado, the comment…&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;I&amp;#8217;ll try to be as objective as I can, but obviously as someone who is invested in Geb I come with a bit of a bias.&lt;/p&gt;

&lt;p&gt;You seem to be mixing up several different issues, which is understandable as the post seems born out of frustration.&lt;/p&gt;

&lt;p&gt;For my mind there are three discrete parts:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;The development environment (the language/framework/constructs you use to express the test)&lt;/li&gt;
&lt;li&gt;The execution environment&lt;/li&gt;
&lt;li&gt;The debugging environment&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;They lines blur, but I think it&amp;#8217;s helpful to think about each part separately. Geb itself only lives in the first arena strictly speaking. How it works in the execution and debugging environment are largely aspects of the associated tooling, with the exception of static diagnostic information.&lt;/p&gt;

&lt;p&gt;So a couple of points:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“I agree that as much testing as possible should be done at as low a level as possible”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What&amp;#8217;s usually missing from this sentiment is the &lt;em&gt;why&lt;/em&gt;. Too many people take this stance because testing at a low level is easier. This, in isolation, is not the right way to think about it. The end goal is always working software, not easy tests. Easy tests work towards working software by making it more likely that tests will be created in the first place and maintained. They are low cost/low value. So for me, low level testing is fine until the accuracy compromist becomes too high. If it doesn&amp;#8217;t create a lot of confidence that the system will work, either because it assumes to much or is not backed up by higher level tests, then the developer is fooling themselves. Passing tests is not the end goal, working software is.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s with that in mind that I usually say to people that we need to “suck it up” to a certain extent with functional tests. You should identify if there is value in having automated tests that verify the end to end behaviour of your system, get a feel for what that value is and act accordingly. Then you can make cost/benefit judgements on how much effort to put into functional testing. Avoiding it because it&amp;#8217;s not as easy as unit testing while not taking the value into account is irresponsible, in my opinion. However, we definitely should harness the frustration and desire for simplicity to make it easier.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Even assuming you can optimise so that the application is running and you can run the test from an IDE then Selenium has to start up a browser instance, queries execute, views need to render, etc”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Selenium doesn&amp;#8217;t &lt;em&gt;have&lt;/em&gt; to start up a browser instance, it&amp;#8217;s possible to use an running browser instance. Also, on modern development machines we should be talking about seconds at most to run queries and render views etc.&lt;/p&gt;

&lt;p&gt;As for the Grails specific issues, you&amp;#8217;re going to face the slow application startup when working with Grails no matter what your development environment. In theory, there&amp;#8217;s no difference between different development environments here, but the difference comes in in execution environments. However, it&amp;#8217;s possible to create an execution environment for Geb tests (run in IDE against a running application) that is equivalent to the Selenium IDE experience.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Geb’s output when a waitFor condition fails is just Condition did not pass in x seconds.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is indeed painful. Even with implicit power asserts it doesn&amp;#8217;t get much better. Providing static diagnostic information for functional tests (i.e. non dynamic like an interactive debugging session) is one of the unsolved problems in this area. I&amp;#8217;m not aware of any tool that has a good approach to this. With Geb our approach is to just dump the browser state, but that information is generally not rich enough. Hopefully someone comes up with a good solution.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Selenese is by no means great in this regard (a humble Condition timed out isn’t much help) but at least you can step back with the Selenium IDE and watch the damn thing not working much more easily.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I think &lt;em&gt;much more easily&lt;/em&gt; is a stretch. You can do the same thing with a Geb/WebDriver test. The only difference being is that the test method is your smallest level of granularity for re-running a part of the test. That&amp;#8217;s a clear advantage that Selenium IDE has; the ability to run a selected portion of the story at any granularity. It seems like this would break down for most stories though as they require context that needs to be run as well.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The most productive I’ve ever been when writing functional tests has been when using Selenium IDE.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;(and the rest of this paragraph and the next)&lt;/p&gt;

&lt;p&gt;There&amp;#8217;s only one point you make here that can&amp;#8217;t be replicated with Geb/WebDriver in an IDE: selecting a portion of the test at any granularity and just running that. Everything else is also possible in an IDE, and is the exact same process you would use to debug other code. These are all points on the execution/debugging environment not the development environment.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Despite these significant failings writing tests in Selenium IDE is very effective. Maintaining a suite of such tests is another matter. Working on a long-running project the failings of Selenese tests start to increase logarithmically.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is &lt;em&gt;the point&lt;/em&gt; for me. Experience has shown that the majority of the cost of a functional test suite comes in maintenance, not initial development. Therefore the sensible thing to do is to optimise for this first and development speed second. Maintenance should be foremost in the developer&amp;#8217;s mind when developing functional test. The PageObject pattern and inline test data are the two best techniquest that I am aware of that help here.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“I’m convinced that the goal of writing tests in the same language as the application is a pretty vapid one. Working inside one’s comfort zone is all very well but too many times I’ve seen things tested using Selenium or Geb that would be better tested with a unit-level JavaScript test.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It&amp;#8217;s not necessarily about using the same language, it&amp;#8217;s about integration and sharing data structures. Equating functional testing to black box testing is incorrect I think. I have no problem with stimulating the system as a user, but poking inside to verify internal state. To me, that&amp;#8217;s more productive and accurate.&lt;/p&gt;

&lt;p&gt;JavaScript unit tests aren&amp;#8217;t a replacement for functional tests. You shouldn&amp;#8217;t be using functional tests to unit test JavaScript, but having JavaScript unit tests doesn&amp;#8217;t relieve you from having functional tests. It can mean you need less though. If a test doesn&amp;#8217;t emulate what a &lt;em&gt;user&lt;/em&gt; does (including the user environment) to a reasonable degree of accuracy it is not a functional test.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“As a Grails developer I’ve looked enviously at how fast tests run in Rails apps but that’s nothing compared to watching a couple of hundred Jasmine tests run in under a second.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I think you&amp;#8217;re comparing apples and oranges here. I&amp;#8217;d have little faith in a system that only has JavaScript unit tests.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“I was at one time convinced that the ability to use loops and conditional statements in Groovy made it a more suitable testing language than Selenese but honestly, how often are such constructs really required for tests?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In my experience, these constructs are more useful when modelling the concept with appropriate abstractions. As interaction with web pages becomes richer (gestures, dragging etc.), I think we&amp;#8217;ll see it become more useful there. That is, one logical interaction may have looping/branching logic internally but we want to model it as one abstraction.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Building Geb content definitions with deeply nested layers of Module types is time consuming &amp;amp; difficult.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I agree. However, when you put the effort in and do this right you get maintainable tests plus a wealth of predefined abstractions to draw on in future tests. That is, high cost/high value. With my Geb hat on, I think we have the best story in this area in terms of provided constructs. What we lack is the shared knowledge and experience to deploy these constructs &lt;em&gt;effectively&lt;/em&gt;. I think every tool that tries to do this has the same problem though. In a word, inexperience.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“I can’t help thinking the page object model approach is coming at the problem from the wrong angle. Instead of abstracting the UI shouldn’t we be abstracting the behaviour?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I think you need both. You can&amp;#8217;t do away with abstracting the UI.&lt;/p&gt;

&lt;p&gt;Geb&amp;#8217;s in a tight spot here in that it has no execution model. This makes it awkward to introduce behaviour abstractions as we&amp;#8217;d have to wrestle the execution control away from the execution framework we are integrating with. Ultimately, this abstraction belongs in JUnit/Spock/whatever. Spock is missing this capability, and that&amp;#8217;s a known problem.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The most impressive Selenium extension I’ve seen is Steve Cresswell’s Natural Language Extensions that layers something like JBehave’s feature definition language on top of Selenese.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Not being a Selenese expert, this seems like it would give you the the behaviour abstractions you desire but you&amp;#8217;d have to either largely abandon UI abstraction or maintain that separately.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;d love to see someone start a project adapting something like Fitnesse or some other natural language based tool to Geb. You&amp;#8217;d get the same behaviour abstraction benefits, but get to use Geb&amp;#8217;s page modelling to maintain the UI abstractions. Hopefully someone starts this.&lt;/p&gt;

&lt;p&gt;As for cucumber, if you want natural language authoring I think it&amp;#8217;s the choice. There are posts out there about people layering it on top of Geb.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m very skeptical of FuncUnit, but not well educated about it. It&amp;#8217;s not clear to me how it fits into an automated build and it seems like it would have a very high mental context switching cost. You also give up on data structure sharing entirely.&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;That&amp;#8217;s it.&lt;/p&gt;

&lt;p&gt;So the take home for me is that we need to spend more effort on the execution and debugging environments for Geb. Perhaps this will be the focus of the &lt;code&gt;0.7.x&lt;/code&gt; series which will be starting soon.&lt;/p&gt;</description><link>http://ldaley.com/post/13251886270</link><guid>http://ldaley.com/post/13251886270</guid><pubDate>Fri, 25 Nov 2011 00:49:00 +1100</pubDate><category>geb</category><category>software</category></item><item><title>Geb Modules and isDisplayed()</title><description>&lt;p&gt;A question recently came up on the Geb user mailing list about checking to see if a module is &lt;em&gt;displayed&lt;/em&gt; on a page. It turns out the concept of &lt;em&gt;displayed&lt;/em&gt; could do with some exploration.&lt;/p&gt;

&lt;p&gt;Say we have the following html…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;p class="a" style="display:none"/&amp;gt;
&amp;lt;p class="b"/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The following assertions will pass…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def a = $("p.a")
def b = $("p.b")
def c = $("p.c")

assert a &amp;amp;&amp;amp; !a.displayed
assert b &amp;amp;&amp;amp; b.displayed
assert !c &amp;amp;&amp;amp; !c.displayed
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So &lt;code&gt;isDisplayed()&lt;/code&gt; means that the navigator matches some content and the &lt;em&gt;first&lt;/em&gt; thing that it has matched is actually visible on the page. &lt;code&gt;$("p.c").displayed&lt;/code&gt; returns &lt;code&gt;false&lt;/code&gt; because it doesn&amp;#8217;t match anything.&lt;/p&gt;

&lt;p&gt;Navigator objects implement the Groovy Truth, so those assertions could be written as…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;assert a.size() != 0 &amp;amp;&amp;amp; !a.displayed
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Modules also implement the Groovy Truth using the same test, so…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ParagraphA extends Module {
    static base = { $("p.a") }
}
class ParagraphB extends Module {
    static base = { $("p.b") }
}
class ParagraphB extends Module {
    static base = { $("p.c") }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now assume we have &lt;code&gt;moduleA&lt;/code&gt;, &lt;code&gt;moduleB&lt;/code&gt; and &lt;code&gt;moduleC&lt;/code&gt; vars that are instances of the corresponding modules, and we can write the following assertions…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;assert moduleA &amp;amp;&amp;amp; !moduleA.$().displayed
assert moduleB &amp;amp;&amp;amp; moduleB.$().displayed
assert !moduleC &amp;amp;&amp;amp; !moduleC.$().displayed
&lt;/code&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;You can get the “base” of a module at anytime with «module».$(), just like you can do relative lookups (i.e. someModule.$(&amp;#8220;p.d&amp;#8221;))&lt;/p&gt;
&lt;/blockquote&gt;</description><link>http://ldaley.com/post/6570075743</link><guid>http://ldaley.com/post/6570075743</guid><pubDate>Thu, 16 Jun 2011 09:56:16 +1000</pubDate><category>software</category><category>geb</category></item><item><title>Using Grails tags where you can't use Grails tags</title><description>&lt;p&gt;Sometimes in a Grails app, you need to call a tag where you can&amp;#8217;t call a tag. This is usually indicative of a bad design in your application so do use the following with caution, but should you absolutely need to… the following is how you can.&lt;/p&gt;

&lt;p&gt;In this example, we are going to add the ability to call tags to a filter to workaround &lt;a href="http://jira.grails.org/browse/GRAILS-6814" title="[#GRAILS-6814] redirect() does not take a 'base' argument link link/createLink - Grails JIRA"&gt;GRAILS-6814&lt;/a&gt;. We want to call the &lt;code&gt;createLink&lt;/code&gt; tag.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Note that GRAILS-6814 has been resolved for Grails 1.4, so this workaround for redirects to a different domain only applies to Grails 1.3 and earlier&lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre&gt;&lt;code&gt;import org.codehaus.groovy.grails.web.pages.GroovyPage
import org.springframework.web.context.request.RequestContextHolder

class HttpsOnlyFilter {

    def gspTagLibraryLookup // need this autowired

    def filters = {
        redirectToHttps(controller: "*", action: "*") {
            before = {
                if (!request.secure &amp;amp;&amp;amp; isSecurePage(controllerName, actionName)) {
                    def link = invokeTag("createLink", [
                        controller: controllerName, 
                        action: actionName, 
                        params: params, 
                        base: "https://secure.domain.com"
                    ]).toString()
                    response.status = 301
                    response.setHeader("Location", link)
                    false
                }
            }
        }
    }

    def invokeTag(name, attrs = [:], body = null) {
        def namespace
        def tagName

        if (name.contains(":")) {
            def split = name.split(":", 2)
            namespace = split[0]
            tagName = split[1]
        } else {
            namespace = GroovyPage.DEFAULT_NAMESPACE
            tagName = name
        }

        GroovyPage.captureTagOutput(gspTagLibraryLookup, namespace, tagName, attrs, body, RequestContextHolder.currentRequestAttributes())
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;invokeTag&lt;/code&gt; method takes; the name of a tag, a map of attributes, and an option body closure and returns a &lt;a href="https://github.com/grails/grails-core/blob/master/grails-web/src/main/groovy/org/codehaus/groovy/grails/web/util/StreamCharBuffer.java"&gt;StreamCharBuffer&lt;/a&gt; (so if you want the content as a &lt;code&gt;String&lt;/code&gt; you new to &lt;code&gt;toString()&lt;/code&gt; the return). Inside the body closure, you can write to the &lt;code&gt;out&lt;/code&gt; stream just like in a tag implementation.&lt;/p&gt;

&lt;p&gt;If the tag name given to &lt;code&gt;invokeTag()&lt;/code&gt; doesn&amp;#8217;t include a namespace, the default &lt;code&gt;g&lt;/code&gt; namespace is used. To invoke a tag in a different namespace, you can use…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;invokeTag("someNamespace:someTag", [param1: 1])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Remember, requiring tags outside of the view layer can be indicative of a design problem so do think long and hard about whether you really need to before using the above. Also, the above will only work in a request environment so if you try to use the above on a background thread were a fake request environment hasn&amp;#8217;t been established it will blow up due to &lt;code&gt;RequestContextHolder.currentRequestAttributes()&lt;/code&gt; returning &lt;code&gt;null&lt;/code&gt;. If you need to setup a fake request environment, you can use &lt;a href="https://github.com/grails/grails-core/blob/master/grails-web/src/main/groovy/grails/util/GrailsWebUtil.java#L162"&gt;GrailsWebUtil.bindMockWebRequest()&lt;/a&gt; to do so.&lt;/p&gt;</description><link>http://ldaley.com/post/5378542618</link><guid>http://ldaley.com/post/5378542618</guid><pubDate>Wed, 11 May 2011 11:40:00 +1000</pubDate><category>software</category><category>grails</category></item><item><title>Always developing Grails apps with https and testing against the WAR</title><description>&lt;p&gt;In response to a number of bugs creeping through to production due to classpath differences and ssl issues, I went about setting up my culprit grails app to always functionally test as a war and with https in both development and testing. Here&amp;#8217;s how to do it.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;It turns out that there are two bugs/issues with the current grails tomcat plugin that get in the way of this objective, so you&amp;#8217;ll have to install the &lt;code&gt;1.3.7.1&lt;/code&gt; version of the tomcat plugin which fixes &lt;a href="http://jira.grails.org/browse/GRAILS-6688"&gt;GRAILS-6688&lt;/a&gt; and &lt;a href="http://jira.grails.org/browse/GRAILS-7488"&gt;GRAILS-7488&lt;/a&gt; for Grails 1.3.x (these issues will be fixed for Grails 1.4).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;Always support https&lt;/h2&gt;

&lt;p&gt;This is quite simple, but perhaps a little tricky to work out. Simply put the following in your &lt;code&gt;scripts/_Events.groovy&lt;/code&gt;…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;eventParseArgumentsEnd = {
    argsMap.https = true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s the only suitable hook that I have found that can be used to force https to be used all the time (i.e. &lt;code&gt;run-app&lt;/code&gt; and &lt;code&gt;test-app&lt;/code&gt;). It&amp;#8217;s a little heavy, but I&amp;#8217;m yet to find a situation where it causes an issue.&lt;/p&gt;

&lt;h2&gt;Always functionally testing with a WAR&lt;/h2&gt;

&lt;p&gt;Again, this is simple. The following goes in &lt;code&gt;scripts/_Events.groovy&lt;/code&gt;…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;eventAllTestsStart = {
    testOptions.war = true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is equivalent to always passing the &lt;code&gt;-war&lt;/code&gt; argument to &lt;code&gt;test-app&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Functional tests and SSL (trust)&lt;/h2&gt;

&lt;p&gt;Depending on how you are functionally testing (and you know you should be using &lt;a href="http://geb.codehaus.org/"&gt;Geb&lt;/a&gt; + &lt;a href="http://spockframework.org"&gt;Spock&lt;/a&gt;) you may have issues with the certificate that Grails will generate for you to serve https. Namely, you might need to go and configure trust settings in all of your functional test browsers etc. If you have multiple CI builds then you are going to have to do this for a lot of certs. Even worse, the cert that Grails generates is stored in the work dir so can be wiped out at any time.&lt;/p&gt;

&lt;p&gt;You can minimise this pain by generating your own cert and having Grails use that when serving https instead of creating one on demand. To do this, you need the following two settings in &lt;code&gt;BuildConfig.groovy&lt;/code&gt;…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;grails.tomcat.keystorePath = "${basedir}/grails-app/conf/httpsKeystore"
grails.tomcat.keystorePassword = "secret"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You of course need to create this keystore with a cert in it, which you can do (in &lt;code&gt;grails-app/conf&lt;/code&gt;) via…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;keytool -genkey -alias localhost -dname CN=localhost,OU=Test,O=Test,C=US -keyalg RSA -validity 365 -storepass key -keystore httpsKeystore -storepass secret -keypass secret
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You now only need to make sure the browser trusts this cert.&lt;/p&gt;

&lt;h2&gt;Why bother?&lt;/h2&gt;

&lt;p&gt;In my case, we were hitting some dependency issues that were due to the development and production classpaths being different so running functional tests against a war minimises this risk because the app is then run in a separate JVM without the Grails build time classpath, making it more production like.&lt;/p&gt;

&lt;p&gt;The application that we were having problems with uses mixed http and https and is also reasonably AJAX heavy. Several issues had crept through with AJAX requests being made on secure pages to non secure pages (which will blow up due to the browser not being willing to compromise security by making the unsecure request).&lt;/p&gt;

&lt;p&gt;These two relatively simple steps get you closer to a production environment if you don&amp;#8217;t have the resourcing, manpower, will etc. to setup an elaborate QA environment for automated testing.&lt;/p&gt;</description><link>http://ldaley.com/post/5235616821</link><guid>http://ldaley.com/post/5235616821</guid><pubDate>Fri, 06 May 2011 13:54:43 +1000</pubDate><category>software</category><category>grails</category></item><item><title>Decorating Constructors with Groovy</title><description>&lt;p&gt;I recently put out a &lt;a href="https://github.com/alkemist/grails-view-models"&gt;new plugin&lt;/a&gt; for Grails that brings something like &lt;a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" title="Model View ViewModel - Wikipedia, the free encyclopedia"&gt;view models&lt;/a&gt; to Grails applications. An interesting feature of this plugin is that it supports direct object instantiation with implicit autowiring. You might think that Grails already support this, but it doesn&amp;#8217;t. Currently, you can directly instantiate domain objects and get autowiring but you can&amp;#8217;t write a constructor and use it here.&lt;/p&gt;

&lt;p&gt;Groovy has had the ability to fiddle with a class&amp;#8217;s constructors via EMC for a while.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Thing {
    def i
    Thing() { i = 1 }
}

assert new Thing().i == 1
Thing.metaClass.constructor = { -&amp;gt; i = 2 }
assert new Thing().i == 2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Trying to augment existing constructors is a bit trickier though. Using the standard EMC API of setting a &lt;code&gt;constructor&lt;/code&gt; property on the meta class, there is no way to access the constructor that is being replaced. To do this you have to dig a bit deeper.&lt;/p&gt;

&lt;p&gt;For the view models plugin I needed to invoke the real constructor, then do some stuff to the new instance. My solution revolves around the &lt;a href="http://groovy.codehaus.org/api/groovy/lang/ExpandoMetaClass.html#registerInstanceMethod(groovy.lang.MetaMethod)"&gt;&lt;code&gt;registerInstanceMethod(groovy.lang.MetaMethod method)&lt;/code&gt;&lt;/a&gt; method of &lt;a href="http://groovy.codehaus.org/api/groovy/lang/ExpandoMetaClass.html" title="ExpandoMetaClass (Groovy 1.7.8)"&gt;ExpandoMetaClass&lt;/a&gt;. After some digging through Groovy, I found that the technique above of setting a &lt;code&gt;constructor&lt;/code&gt; property on the meta class boils down to just attaching an instance &lt;code&gt;MetaMethod&lt;/code&gt; with a method name of &lt;code&gt;&amp;lt;init&amp;gt;&lt;/code&gt; which is the name Groovy uses for constructors. So what we can do is subclass &lt;code&gt;groovy.lang.MetaMethod&lt;/code&gt; to get our custom behaviour, which looks like this…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package grails.plugin.viewmodels.constructor;

import java.lang.InstantiationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import groovy.lang.MetaMethod;
import org.codehaus.groovy.reflection.CachedClass;
import org.codehaus.groovy.reflection.ReflectionCache;

public class DecoratingMetaConstructor&amp;lt;T&amp;gt; extends MetaMethod {

    final private Constructor&amp;lt;T&amp;gt; constructor;
    final private ConstructionDecorator&amp;lt;T&amp;gt; decorator;

    public DecoratingMetaConstructor(Constructor&amp;lt;T&amp;gt; constructor, ConstructionDecorator&amp;lt;T&amp;gt; decorator) {
        super(decorator.getSignature(constructor));

        this.constructor = constructor;
        this.decorator = decorator;
    }

    public Constructor&amp;lt;T&amp;gt; getConstructor() {
        return constructor;
    }

    public int getModifiers() {
        return constructor.getModifiers();
    }

    public String getName() {
        return "&amp;lt;init&amp;gt;";
    }

    public Class&amp;lt;T&amp;gt; getReturnType() {
        return constructor.getDeclaringClass();
    }

    public CachedClass getDeclaringClass() {
        return ReflectionCache.getCachedClass(constructor.getDeclaringClass());
    }

    public Object invoke(Object object, Object[] arguments) {
        Object[] transformedArgs = decorator.transformArgs(arguments);
        T instance = instantiate(transformedArgs);
        decorator.decorate(instance, arguments, transformedArgs);
        return instance;
    }

    protected T instantiate(Object[] arguments) {
        try {
            return decorator.transformConstructor(constructor).newInstance(arguments);
        } catch (InstantiationException e) {
            throw new RuntimeException("Failed to invoke constructor " + constructor + " with args: " + arguments, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to invoke constructor " + constructor + " with args: " + arguments, e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Failed to invoke constructor " + constructor + " with args: " + arguments, e);
        }
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A lot of that is just satisfying the &lt;code&gt;MetaMethod&lt;/code&gt; methods. What&amp;#8217;s of interest to us is that we take a constructor object, and a &lt;em&gt;decorator&lt;/em&gt; which is an interface that we provide…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package grails.plugin.viewmodels.constructor;

import java.lang.reflect.Constructor;

public interface ConstructionDecorator&amp;lt;T&amp;gt; {

    public Object[] transformArgs(Object[] args);

    public void decorate(T instance, Object[] originalArgs, Object[] transformedArgs);

    public Class&amp;lt;?&amp;gt;[] getSignature(Constructor&amp;lt;T&amp;gt; constructor);

    public Constructor&amp;lt;T&amp;gt; transformConstructor(Constructor&amp;lt;T&amp;gt; constructor);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The decorator can supply a different set of args for the actual &lt;code&gt;Constructor&lt;/code&gt; to those that were given to the invocation, supply a different &lt;code&gt;Constructor&lt;/code&gt; instance to use at instantiation time and/or do something with the instance after it has been created.&lt;/p&gt;

&lt;p&gt;We can use this mechanism to write a &lt;em&gt;construction decorator&lt;/em&gt; that performs autowiring…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package grails.plugin.viewmodels.constructor;

import java.lang.reflect.Constructor;
import org.springframework.context.ApplicationContext;

public class AutowiringConstructionDecorator&amp;lt;T&amp;gt; extends ConstructionDecoratorSupport&amp;lt;T&amp;gt; {

    final private Autowirer autowirer;

    public AutowiringConstructionDecorator(ApplicationContext applicationContext) {
        this(new Autowirer(applicationContext));
    }

    public AutowiringConstructionDecorator(Autowirer autowirer) {
        this.autowirer = autowirer;
    }

    public void decorate(T instance, Object[] givenArgs, Object[] transformedArgs) {
        autowirer.autowire(instance);
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;Autowirer&lt;/code&gt; takes care of the actual autowiring details, which aren&amp;#8217;t of much interest here (see the class &lt;a href="https://github.com/alkemist/grails-view-models/blob/master/src/java/grails/plugin/viewmodels/constructor/Autowirer.java"&gt;here&lt;/a&gt; if you want).&lt;/p&gt;

&lt;p&gt;So we can now take a class, and make all of it&amp;#8217;s constructors implicitly perform autowiring by doing something like this…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def autowiringDecorator = new AutowiringConstructionDecorator(grailsApplication.mainContext)

for (constructor in MyThing.constructors) {
    MyThing.metaClass.registerInstanceMethod(new DecoratingMetaConstructor(constructor, autowiringDecorator))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Interestingly, I was able to use the same decoration mechanism to enable hot reloading support by obtaining the newest version of the constructor from the class loader in the Grails application that has the newest version of the class…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package grails.plugin.viewmodels.constructor;

import java.lang.reflect.Constructor;

class ReloadCapableConstructionDecorator&amp;lt;T&amp;gt; extends ConstructionDecoratorSupport&amp;lt;T&amp;gt; {

    private final ClassLoader classLoader;

    public ReloadCapableConstructionDecorator(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public Constructor&amp;lt;T&amp;gt; transformConstructor(Constructor&amp;lt;T&amp;gt; constructor) {
        try {
            Class&amp;lt;T&amp;gt; originalClassVersion = constructor.getDeclaringClass();
            Class&amp;lt;T&amp;gt; newestClassVersion = (Class&amp;lt;T&amp;gt;)classLoader.loadClass(originalClassVersion.getName());

            return newestClassVersion.getConstructor(constructor.getParameterTypes());
        } catch (NoSuchMethodException e) {
            return constructor;
        } catch (ClassNotFoundException e) {
            return constructor;
        }
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The details of why this is needed isn&amp;#8217;t worth going into now, what&amp;#8217;s important is the fact that you could do some rather interesting stuff here.&lt;/p&gt;

&lt;p&gt;If you find you have the need to decorate existing constructors as opposed to completely replacing them, it&amp;#8217;s probably worth taking a look at what&amp;#8217;s in the view-models plugin and either stealing it verbatim or adapting to your own purposes.&lt;/p&gt;

&lt;p&gt;The relavant code and gory details can be found &lt;a href="https://github.com/alkemist/grails-view-models/tree/master/src/java/grails/plugin/viewmodels/constructor"&gt;here&lt;/a&gt;.&lt;/p&gt;</description><link>http://ldaley.com/post/3634626058</link><guid>http://ldaley.com/post/3634626058</guid><pubDate>Fri, 04 Mar 2011 15:54:20 +1100</pubDate><category>software</category><category>grails</category><category>groovy</category></item><item><title>Spock's @AutoCleanup feature</title><description>&lt;p&gt;You may have missed this little gem that was added to Spock in the 0.5 release…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang

class InputStreamSpec extends Specification {

    @AutoCleanup
    def input = new FileInputStream("myfile.txt")

    def "some input stream tests"() {
        // …
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;a href="http://code.google.com/p/spock/source/browse/trunk/spock-core/src/main/java/spock/lang/AutoCleanup.java"&gt;&lt;code&gt;spock.lang.AutoCleanup&lt;/code&gt;&lt;/a&gt; annotation works via &lt;a href="http://ldaley.com/post/971946675/annotation-driven-extensions-with-spock" title="LD."&gt;Spock&amp;#8217;s extension mechanism&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s have a look at the documentation for &lt;code&gt;@AutoCleanup&lt;/code&gt; (taken from the JavaDoc)…&lt;/p&gt;

&lt;blockquote&gt;
    &lt;h4&gt;spock.lang.AutoCleanup&lt;/h4&gt;
    &lt;p&gt;Automatically cleans up the object stored in the annotated field or property at the end of its life time. More precisely, auto-cleanup of an object has the same effect as, and serves as a convenient replacement for, calling the object&amp;#8217;s &lt;tt&gt;close&lt;/tt&gt; method at the end of the spec&amp;#8217;s &lt;tt&gt;cleanup&lt;/tt&gt; method. &lt;tt&gt;@Shared&lt;/tt&gt; objects are cleaned up at the end of the spec&amp;#8217;s &lt;tt&gt;cleanupSpec&lt;/tt&gt; method.&lt;/p&gt;
    &lt;h4&gt;Customizing how cleanup is performed&lt;/h4&gt;
    &lt;p&gt;By default, an object is cleaned up by invoking its parameterless close() method (which is assumed to exist); visibility and return type of this method are irrelevant. If some other method should be called instead, override the annotation&amp;#8217;s &lt;tt&gt;value&lt;/tt&gt; attribute:&lt;/p&gt;
    &lt;pre&gt;@AutoCleanup("dispose") // invoke the object's "dispose" method&lt;/pre&gt;
    &lt;h4&gt;Cleaning up multiple objects&lt;/h4&gt;
    &lt;p&gt;If multiple fields or properties are annotated with @AutoCleanup, their objects are cleaned up sequentially in reverse field/property declaration order, starting from the most derived class and walking up the inheritance chain.&lt;/p&gt;
    &lt;h4&gt;Handling of exceptions during cleanup&lt;/h4&gt;
    &lt;p&gt;If a cleanup operation fails with an exception, the exception is reported (just as if it had occurred in a &lt;tt&gt;cleanup&lt;/tt&gt; or &lt;tt&gt;cleanupSpec&lt;/tt&gt; method) and cleanup proceeds with the next annotated object. To prevent cleanup exceptions from being reported, override the annotation&amp;#8217;s &lt;tt&gt;quiet&lt;/tt&gt; attribute:&lt;/p&gt;
    &lt;pre&gt;@AutoCleanup(quiet = true) // don't report exceptions&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;I find this extremely handy when testing some asynchronous code where I need an &lt;a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executor.html" title="Executor (Java 2 Platform SE 5.0)"&gt;Executor&lt;/a&gt; as part of test fixture…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang.*
import java.util.concurrent.Executors

class AsyncSpec extends Specification {

    @AutoCleanup("shutdown")
    def executor = Executors.newCachedThreadPool()

    def "some async bits"() {

    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Over and above being very convenient, &lt;code&gt;@AutoCleanup&lt;/code&gt; is great because it makes it easier to get your fixture setup out of your feature specifications and to also group fixture setup/teardown logic in one place.&lt;/p&gt;</description><link>http://ldaley.com/post/3133819681</link><guid>http://ldaley.com/post/3133819681</guid><pubDate>Sun, 06 Feb 2011 12:22:53 +1100</pubDate><category>software</category><category>spock</category></item><item><title>Disabling Grails plugin upgrade confirmation </title><description>&lt;p&gt;Quick one…&lt;/p&gt;

&lt;p&gt;If you want to permanently disable plugin version change confirmations (e.g. when another developer has changed a plugin version in &lt;code&gt;BuildConfig.groovy&lt;/code&gt;), simply add this to your &lt;code&gt;scripts/_Events.groovy&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def resolveDependenciesWasInteractive = false
eventResolveDependenciesStart = {
    resolveDependenciesWasInteractive = isInteractive
    isInteractive = false
}

eventResolveDependenciesEnd = {
    isInteractive = resolveDependenciesWasInteractive
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Annoying messages be gone.&lt;/p&gt;</description><link>http://ldaley.com/post/2616518761</link><guid>http://ldaley.com/post/2616518761</guid><pubDate>Thu, 06 Jan 2011 12:44:15 +1100</pubDate><category>grails</category><category>software</category></item><item><title>Spock's new matching support</title><description>&lt;p&gt;Spock has an interesting new feature coming in 0.5 (but its available now in recent builds of 0.5-SNAPSHOT) integrating the &lt;a href="http://code.google.com/p/hamcrest/"&gt;Hamcrest matching library&lt;/a&gt;, which is an API for testing that something meets certain criteria. It&amp;#8217;s always been possible to use Hamcrest with Spock but there is now a more convenient syntax. The expressiveness of Groovy generally makes Hamcrest not quite as generally useful as it would be when testing with plain Java, but it can still make your tests more concise and expressive when you have complex matching to do.&lt;/p&gt;

&lt;p&gt;A classic example is for matching a value against another value within a certain error margin. Hamcrest comes with the &lt;a href="http://www.jmock.org/javadoc/2.0.0/org/hamcrest/Matchers.html#closeTo%28double%2C%20double%29"&gt;&lt;code&gt;closeTo&lt;/code&gt;&lt;/a&gt; matcher for this. This is how you might use it in a JUnit test…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import static org.hamcrest.Matchers.closeTo
import static org.hamcrest.MatcherAssert.assertThat

class HamcrestTests extends GroovyTestCase {
    def testIt() {
        assertThat(1.9d, closeTo(2, 0.5))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This test will pass because the actual value &lt;code&gt;1.9d&lt;/code&gt; (the &lt;code&gt;d&lt;/code&gt; tells groovy it&amp;#8217;s a &lt;code&gt;Double&lt;/code&gt; and not a &lt;code&gt;BigDecimal&lt;/code&gt;) is within ± 0.5 of 2. The &lt;code&gt;closeTo&lt;/code&gt; method is what&amp;#8217;s known as a &lt;em&gt;matcher factory&lt;/em&gt; (i.e. it returns an instance of &lt;a href="http://www.jmock.org/javadoc/2.0.0/org/hamcrest/Matcher.html"&gt;&lt;code&gt;org.hamcrest.Matcher&lt;/code&gt;&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Using Spock&amp;#8217;s new convenient matcher syntax, we write the above as…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang.Specification
import static org.hamcrest.Matchers.closeTo

class HamcrestSpec extends Specification {
    void "test closeTo"() {
        expect:
        1.9d closeTo(2, 0.5)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nice and concise isn&amp;#8217;t it. The syntax is essentially…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;«value» «org.hamcrest.Matcher»
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is also another variant…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang.Specification
import static spock.util.matcher.MatcherSupport.that
import static org.hamcrest.Matchers.closeTo

class HamcrestSpec extends Specification {
    void "test closeTo"() {
        expect:
        that 1.9d, closeTo(2, 0.5)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This syntax has the advantage that it can be combined with the &lt;code&gt;assert&lt;/code&gt; keyword so can be used outside of the &lt;code&gt;then&lt;/code&gt;/&lt;code&gt;expect&lt;/code&gt; blocks (which the shorthand version can&amp;#8217;t).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang.Specification
import static spock.util.matcher.MatcherSupport.that
import static org.hamcrest.Matchers.closeTo

class HamcrestSpec extends Specification {
    void "test closeTo"() {
        setup:
        assert that(1.9d, closeTo(2, 0.5))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Custom Matchers&lt;/h2&gt;

&lt;p&gt;As previously mentioned, a lot of the stock matchers that come with Hamcrest are not as useful in Groovy as they are in Java due to Groovy&amp;#8217;s many convenience methods and expressive syntax. However, you can easily write your own Hamcrest matchers that are particular to your problem domain to make your tests more concise and maintainable.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s use the example of a Grails application that lets user&amp;#8217;s read books online. There is a very simple security model; users and books both belong to &lt;em&gt;groupings&lt;/em&gt; and a user must belong to at least one grouping that a book belows to to be allowed to read it. Here is what our domain looks like…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Book {
    String name
    static hasMany = [groupings: Grouping]
    static belongsTo = Grouping
}
class User {
    String name
    static hasMany = [groupings: Grouping]
    static belongsTo = Grouping
}
class Grouping {
    String name
    static hasMany = [books: Book, users: User]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We could write a custom matcher that checks if a given user can read a given book…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang.*
import grails.plugin.spock.*
import org.hamcrest.BaseMatcher
import org.hamcrest.Description
import static org.hamcrest.Matchers.not

class ReadabilitySpec extends IntegrationSpec {
    def "test readability"() {
        when:
        def user = new User(name: "u1").save()
        def book1 = new Book(name: "b1").save()
        def book2 = new Book(name: "b1").save()

        def grouping1 = new Grouping(name: "g1")
        grouping1.addToUsers(user)
        grouping1.addToBooks(book1)
        grouping1.save()

        def grouping2 = new Grouping(name: "g2")
        grouping2.addToBooks(book2)
        grouping2.save()

        then:
        user canRead(book1)
        user not(canRead(book2))
    }

    def canRead(book) {
        [
            matches: { user -&amp;gt; user.groupings.any { it in book.groupings } },
            describeTo: { Description description -&amp;gt; description.appendText("user in one of groupings ${book.groupings*.name}") }
        ] as BaseMatcher
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we have implemented the &lt;em&gt;canRead&lt;/em&gt; matcher factory as an instance method on our spec class. We are also using Groovy&amp;#8217;s ability to convert maps into objects that either extend a given class or implement an interface. Here we create a map with the methods that we need to override from the &lt;a href="http://www.jmock.org/javadoc/2.0.0/org/hamcrest/BaseMatcher.html" title="BaseMatcher"&gt;&lt;code&gt;org.hamcrest.BaseMatcher&lt;/code&gt;&lt;/a&gt; class then use &lt;code&gt;as BaseMatcher&lt;/code&gt; to have Groovy create a dynamic subclass for us at runtime (note that this has nothing to do with Spock&amp;#8217;s matching support, I am just using it here for conciseness).&lt;/p&gt;

&lt;p&gt;We could factor out our custom matcher into a real class and perhaps move the factory method to a separate class as a static method, making it reusable across our project. You could quite easily build up a library of convenient matchers that express your problem domain.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Spock&amp;#8217;s new Hamcrest support is yet another great feature that makes your testing easier and more concise. It&amp;#8217;s another great tool to have in your bag of tricks when writing tests. For more info and examples, you can check out the &lt;a href="http://code.google.com/p/spock/source/browse/trunk/spock-specs/src/test/groovy/org/spockframework/smoke/condition/HamcrestMatchers.groovy"&gt;test case in the Spock project that exercises this stuff&lt;/a&gt;.&lt;/p&gt;</description><link>http://ldaley.com/post/1281387832</link><guid>http://ldaley.com/post/1281387832</guid><pubDate>Sun, 10 Oct 2010 16:24:00 +1100</pubDate><category>software</category><category>grails</category><category>spock</category></item><item><title>Getting more out of Property Override Configuration</title><description>&lt;p&gt;The “&lt;a href="http://grails.org/doc/1.3.x/guide/14.%20Grails%20and%20Spring.html#14.6%20Property%20Override%20Configuration"&gt;Property Override Configuration&lt;/a&gt;” feature is an extremely useful technique for Grails applications. It allows you to specify the values for bean properties in your application configuration, which can be done &lt;a href="http://grails.org/doc/1.3.x/guide/3.%20Configuration.html#3.4%20Externalized%20Configuration"&gt;externally&lt;/a&gt; and/or in an &lt;a href="http://grails.org/doc/1.3.x/guide/3.%20Configuration.html#3.2%20Environments"&gt;environment sensitive&lt;/a&gt; manner.&lt;/p&gt;

&lt;p&gt;For example, we could easily control the number of simultaneous connections a particular service is allowed to make to a particular &lt;em&gt;thing&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Here is our fictitious service…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ThingService {
    def maxConnections
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In our Config.groovy we might have…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beans {
    thingService {
        maxConnections = 10
    }
}

environments {
    test {
        beans {
            thingService {
                // only use 1 connection when testing
                maxConnections = 1 
            }
        }
    }
    production {
        // Load extra config from external location in production
        grails.config.locations = ["classpath:thing-config.groovy"]
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;On the production classpath we might have a file called “&lt;code&gt;thing-config.groovy&lt;/code&gt;” that has…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beans.thingService.maxConnections = 100
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So we no have a default value of &lt;code&gt;10&lt;/code&gt; for our &lt;code&gt;maxConnections&lt;/code&gt; property, but overridden in test with a value of &lt;code&gt;1&lt;/code&gt; and overridden in production with a value of &lt;code&gt;100&lt;/code&gt;. We can also change this value without a recompile in production (though you will need a restart).&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s all well and good and pretty handy, but you can take it slightly further once you realise how this feature works.&lt;/p&gt;

&lt;h2&gt;Type Conversion&lt;/h2&gt;

&lt;p&gt;Property Override Configuration works at the bean definition level in Spring. This means that the value you specify is &lt;strong&gt;not&lt;/strong&gt; directly assigned to the corresponding property on the bean in question, but rather is added to the bean definition before Spring goes to work creating your beans (which is effectively the same as changing the original bean definition). This means that you can take advantage of Spring&amp;#8217;s rich type conversion features to do some rather cool things.&lt;/p&gt;

&lt;p&gt;For example, we can make dealing with the filesystem easier by combining Spring&amp;#8217;s resource support with the Property Override Configuration mechanism. Let&amp;#8217;s assume we have a service that wants to read a text file that is on the classpath.&lt;/p&gt;

&lt;p&gt;Here is our service…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class TextFileReadingService {
    File textFile
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To populate that property you could either write the code yourself to create the instance, define a bean named &lt;code&gt;textFile&lt;/code&gt; in &lt;code&gt;resources.groovy&lt;/code&gt; and let autowiring set things up, or use Property Override Configuration. If we want to use Property Override Configuration, you might first try…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beans {
    textFileReadingService {
        textFile = new File(this.class.classLoader.getResource("theTextFile.txt").toURI())
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While that will work, there is an easier way…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beans {
    textFileReadingService {
        textFile = "classpath:theTextFile.txt"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works because Spring implicitly converts the &lt;code&gt;String&lt;/code&gt; value we have given to a &lt;code&gt;File&lt;/code&gt; object for us, and in doing this treats values with certain prefixes specially. This is part of &lt;a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/resources.html"&gt;Spring&amp;#8217;s resource abstractions&lt;/a&gt;. Another useful prefix is “&lt;code&gt;context:&lt;/code&gt;”, which resolves a file path relative to the root of the web app…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beans {
    textFileReadingService {
        textFile = "context:js/jquery.js"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Your own beans&lt;/h2&gt;

&lt;p&gt;Note that Property Override Configuration is particularly useful when working with beans that we don&amp;#8217;t define ourselves, such as services, taglibs, controllers etc. If we were defining our own beans and did not need environment sensitivity or externalisation of the value, we could use the same type conversion facilities when definining our beans directly.&lt;/p&gt;

&lt;p&gt;If we had a class in &lt;code&gt;src/groovy&lt;/code&gt; that looked like…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class TextFileReader {
    File textFile
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We could create a Spring bean for it like so in &lt;code&gt;resources.groovy&lt;/code&gt;…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beans = {
    textFileReader(TextFileReader) {
        textFile = "context:js/jquery.js"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The point of this example being to illustrate that type conversion is not unique to Property Override Configuration.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Property Override Configuration is a surprisingly useful feature that is generally under publicised. It&amp;#8217;s worth adding to your arsenal of techniques, especially combined with the type conversion that Spring offers.&lt;/p&gt;</description><link>http://ldaley.com/post/1253952347</link><guid>http://ldaley.com/post/1253952347</guid><pubDate>Wed, 06 Oct 2010 15:41:57 +1100</pubDate><category>grails</category><category>software</category></item><item><title>Painless Page Identification with Geb &amp; Grails</title><description>&lt;p&gt;This will be a discussion of a handy pattern to use to make page identification simple and easy when working with &lt;a href="http://geb.codehaus.org/" title="Geb - Groovy Browser Automation"&gt;Geb&lt;/a&gt; and &lt;a href="http://www.grails.org/" title="Grails - The search is over."&gt;Grails&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Geb and Page Identification&lt;/h2&gt;

&lt;p&gt;Geb supports (and encourages) using the &lt;a href="http://geb.codehaus.org/manual/latest/intro.html#the_page_object_pattern" title="The Book Of Geb - Introduction"&gt;Page Object Pattern&lt;/a&gt;. An aspect of this is having someway of being able to verify that the page object actually does represent the page that the browser is at. Consider filling out a form. When you submit the form you might expect to go to a confirmation page, but because of a validation error you get returned to the form page. In your test code after submitting the form you go on testing for things on the page and the results can be confusing. The best thing to do before testing parts of the page is to test that the page is indeed what you expect it to be. There are other reasons for page identification, but this is the main one.&lt;/p&gt;

&lt;p&gt;Geb implements page identification through it&amp;#8217;s “&lt;a href="http://geb.codehaus.org/manual/latest/pages.html#at_verification" title="The Book Of Geb - Pages"&gt;at checking&lt;/a&gt;”. In short, pages declare an “at” closure that contains some checks of the page structure, and returns &lt;code&gt;true&lt;/code&gt; if the actual browser page is what the page object represents.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import geb.*

class ManualPage extends Page {
    static at = { $("h1", text: contains("Manual")) }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This “at check” is used implicitly when using the browser &lt;code&gt;at(«PageClass»)&lt;/code&gt; method…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Browser.driver {
    to ManualPage
    assert at(ManualPage) 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;at(«PageClass»)&lt;/code&gt; method does two things:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Checks the browser&amp;#8217;s page object is an instance of the given class&lt;/li&gt;
&lt;li&gt;Checks the browser&amp;#8217;s page object&amp;#8217;s at checker returns &lt;code&gt;true&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;The use of a &lt;code&gt;Class&lt;/code&gt; with the &lt;code&gt;at()&lt;/code&gt; method may seem strange. After using Geb for a short amount of time the reasons do become clear. Primarily, your test code is likely to not to declare page changes (&lt;a href="http://geb.codehaus.org/manual/latest/pages.html#to" title="The Book Of Geb - Pages"&gt;such as when content declares a &lt;code&gt;to&lt;/code&gt; property&lt;/a&gt;). This means that asserting the &lt;em&gt;type&lt;/em&gt; of the current page object becomes important.&lt;/p&gt;

&lt;p&gt;Writing a good at checker can be hard at times. You want to test &lt;em&gt;enough&lt;/em&gt; so that you are sure the page is a match, yet you don&amp;#8217;t want to test &lt;em&gt;too much&lt;/em&gt; to make your checks fragile.&lt;/p&gt;

&lt;h2&gt;Grails and Conventions&lt;/h2&gt;

&lt;p&gt;Fortunately, Grails&amp;#8217; controller/action convention makes identifying pages cost free and definitive (for almost all cases). The trick lies in the &lt;code&gt;controllerName&lt;/code&gt; and &lt;code&gt;actionName&lt;/code&gt; variables being available in each action&amp;#8217;s view implicitly. This allows you to make your Grails GSP &lt;em&gt;templates&lt;/em&gt; look something like this…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta name="pageId" content="${controllerName}.${actionName}" /&amp;gt;
  …
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  …
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Every view generated from a controller action in your application now has a unique identifier embedded into the page in an unobtrusive manner.&lt;/p&gt;

&lt;h2&gt;Action Page Objects&lt;/h2&gt;

&lt;p&gt;Geb goes out of it&amp;#8217;s way to support using inheritance with page objects. This means that you can define an at checker in a common base class that reads our meta &lt;code&gt;pageId&lt;/code&gt; property and have that used for each subclass.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import geb.*

abstract class GrailsPage extends Page {

    // To be overridden by subclasses
    static controller = null
    static action = null

    static at = {
        // delegate here is the original page _instance_ (i.e. the subclass)

        def expectedPageControllerName = delegate.class.controller
        if (expectedPageControllerName == null) {
            throw new IllegalStateException("${delegate.class} forgot to declare which controller it belongs to")
        }

        def expectedPageActionName = delegate.class.action
        if (expectedPageActionName == null) {
            throw new IllegalStateException("${delegate.class} forgot to declare which action it is")
        }

        def actualPageControllerName = controllerName
        def actualPageActionName = actionName

        assert actualPageControllerName == expectedPageControllerName
        assert actualPageActionName == expectedPageActionName

        true // at checkers must return true
    }

    static content = {
        pageId { $("meta", name: "pageId").@content }
        controllerName { pageId.split('\\.')[0] }
        actionName { pageId.split('\\.')[1] }
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we do three things:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;declare &lt;code&gt;static&lt;/code&gt; ‘controller’ and ‘action’ properties that subclasses will populate (more on this later)&lt;/li&gt;
&lt;li&gt;declare an “at checker” that compares the declared controller/action against those in the page&lt;/li&gt;
&lt;li&gt;declare what the &lt;code&gt;controllerName&lt;/code&gt; and &lt;code&gt;actionName&lt;/code&gt; bits of content on the page are (&lt;a href="http://geb.codehaus.org/manual/latest/pages.html#the_content_dsl" title="The Book Of Geb - Pages"&gt;consult the Book Of Geb&lt;/a&gt; for more on this content DSL)&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;We now have a rock solid page identification mechanism that from here on in in the development and testing of our application costs us almost nothing. The only thing you need to do when writing new page objects is set the &lt;code&gt;controller&lt;/code&gt; and &lt;code&gt;action&lt;/code&gt; static properties…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ViewCartPage extends GrailsPage {
    static controller = "cart"
    static action = "view"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or in the case where all your actions for a particular controller share content, you may want to have an abstract base class for all actions of that controller…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;abstract class CartPage extends GrailsPage {
    static controller = "cart"
}

class ViewCartPage extends CartPage {
    static action = "view"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Geb and Inheritance (and Groovy)&lt;/h2&gt;

&lt;p&gt;This is made possible by Geb supporting &lt;a href="http://geb.codehaus.org/manual/latest/pages.html#inheritance" title="The Book Of Geb - Pages"&gt;inheritance of content definitions&lt;/a&gt; (content definitions are merged) and Groovy supporting a dynamic resolution of static methods and properties.&lt;/p&gt;

&lt;p&gt;Given the above classes, the following works…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;assert ViewCartPage.controller == "cart"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, if we were calling this from Java, it &lt;strong&gt;would not&lt;/strong&gt; work. In Java, static methods/properties are never inherited like they are for all intents and purposes in Groovy. This means that when requesting a page class&amp;#8217;s “at checker” it will search the inheritance hierarchy for one (e.g. &lt;code&gt;assert ViewCartPage.at == GrailsPage.at&lt;/code&gt;). This also means that at any point in the inheritance hierarchy you can override any static method/property defined in a super class (but it only works if calling from Groovy).&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;We discussed a useful pattern for page identification (“at checking” in Geb parlance) with Geb and Grails. I have used this pattern in anger and have found it to be very useful. Give it a try.&lt;/p&gt;</description><link>http://ldaley.com/post/1013531080</link><guid>http://ldaley.com/post/1013531080</guid><pubDate>Thu, 26 Aug 2010 19:22:00 +1000</pubDate><category>software</category><category>grails</category><category>geb</category></item><item><title>Annotation Driven Extensions With Spock</title><description>&lt;p&gt;The following is an introduction to writing extensions with everybody&amp;#8217;s favourite testing tool &lt;a href="http://spockframework.org"&gt;Spock&lt;/a&gt;. Like all things in Spock, extensions are easy to use and require little ceremony. We are going to build an extension that times various parts of test execution and blindly writes the times to standard out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Please note that the API we are going to go through should not be considered stable/final&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We are building against Spock 0.5-SNAPSHOT and the following APIs may change on the road to 1.0.&lt;/p&gt;

&lt;h2&gt;Annotation Driven&lt;/h2&gt;

&lt;p&gt;Our extension is going to be annotation driven. We are going to provide an annotation that users can place on various parts of their specs. At the core of this is the &lt;code&gt;IAnnotationDrivenExtension&lt;/code&gt; contract…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package org.spockframework.runtime.extension;

import java.lang.annotation.Annotation;
import org.spockframework.runtime.model.*;

public interface IAnnotationDrivenExtension&amp;lt;T extends Annotation&amp;gt; {
  void visitSpecAnnotation(T annotation, SpecInfo spec);
  void visitFeatureAnnotation(T annotation, FeatureInfo feature);
  void visitFixtureAnnotation(T annotation, MethodInfo fixtureMethod);
  void visitFieldAnnotation(T annotation, FieldInfo field);
  void visitSpec(SpecInfo spec);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You&amp;#8217;ll notice that (almost) all of Spock&amp;#8217;s internals are implemented in Java. In this exercise we will implement our extension bits in Groovy.&lt;/p&gt;

&lt;p&gt;Annotation driven extensions implement the &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern" title="Visitor pattern - Wikipedia, the free encyclopedia"&gt;Visitor Pattern&lt;/a&gt;, and Spock will invoke your visitation method for each annotation of your type present on the spec (We&amp;#8217;ll discuss the &lt;code&gt;visitSpec()&lt;/code&gt; method later).&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;visitSpecAnnotation()&lt;/code&gt; - is called when the spec class is annotated.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;visitFeatureAnnotation()&lt;/code&gt; - is called for each “feature” (i.e test method).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;visitFixtureAnnotation()&lt;/code&gt; - is called for each of the &lt;code&gt;setupSpec()&lt;/code&gt;, &lt;code&gt;setup()&lt;/code&gt;, &lt;code&gt;cleanup()&lt;/code&gt; and &lt;code&gt;cleanupSpec()&lt;/code&gt; methods that are annotated.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;visitFieldAnnotation()&lt;/code&gt; - is called for each spec instance variable.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;visitSpec()&lt;/code&gt; - is always called &lt;strong&gt;after&lt;/strong&gt; all of the visitation methods. This allows you to collect a model while visiting, then decorate the spec in some manner.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;These methods all take the annotation instance and an info object which describes the annotated thing. For more detail on each of these info types above what we will go through in this exercise, &lt;a href="http://code.google.com/p/spock/source/browse/#svn/trunk/spock-core/src/main/java/org/spockframework/runtime/model"&gt;check them out in the Spock source&lt;/a&gt;. They are pretty straightforward.&lt;/p&gt;

&lt;h3&gt;The Annotation&lt;/h3&gt;

&lt;p&gt;We need to wire our annotation up to our extension. We declare our annotation like normal, but annotate it with the &lt;code&gt;IAnnotationDrivenExtension&lt;/code&gt; implementation that backs it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import java.lang.annotation.*
import org.spockframework.runtime.extension.ExtensionAnnotation

@Retention(RetentionPolicy.RUNTIME)
@Target([ElementType.TYPE, ElementType.METHOD])

@ExtensionAnnotation(TimingExtension)

public @interface Time {}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we have declared a new annotation called &lt;code&gt;@Time&lt;/code&gt; that takes no parameters and can be placed on types (in our context, the spec class) and methods. The &lt;code&gt;@ExtensionAnnotation&lt;/code&gt; meta annotation is how tell Spock who deals with the &lt;code&gt;@Time&lt;/code&gt; annotation.&lt;/p&gt;

&lt;h3&gt;The Extension&lt;/h3&gt;

&lt;p&gt;Now we need to actual implement our extension. As you would expect, Spock provides a &lt;code&gt;AbstractAnnotationDrivenExtension&lt;/code&gt; super class that we can use. This allows us to only implement the methods we need to. In our case, we don&amp;#8217;t need the &lt;code&gt;visitFieldAnnotation()&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import org.spockframework.runtime.extension.AbstractAnnotationDrivenExtension
import org.spockframework.runtime.model.SpecInfo
import org.spockframework.runtime.model.FeatureInfo
import org.spockframework.runtime.model.MethodInfo

class TimingExtension extends AbstractAnnotationDrivenExtension&amp;lt;Time&amp;gt; {
  def timeSpec = false
  def timedFeatures = []

  void visitSpecAnnotation(Time annotation, SpecInfo spec) {
    timeSpec = true
  }

  void visitFeatureAnnotation(Time annotation, FeatureInfo feature) {
    timedFeatures &amp;lt;&amp;lt; feature.name
  }

  void visitSpec(SpecInfo spec) {
    spec.addListener(new TimingRunListener(timeSpec, timedFeatures)
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we simply collect information on which things we are timing, then add a run &lt;em&gt;listener&lt;/em&gt; (explained below) that will do the timing.&lt;/p&gt;

&lt;p&gt;The implementation of the visitation methods in &lt;code&gt;AbstractAnnotationDrivenExtension&lt;/code&gt; always throw an &lt;code&gt;org.spockframework.runtime.InvalidSpecException&lt;/code&gt;. Our annotation can legally be placed on any fixture methods according to it&amp;#8217;s definition, but that doesn&amp;#8217;t make sense in the context of our extension. Because we have not overridden the &lt;code&gt;visitFixtureAnnotation()&lt;/code&gt; method in our extension, if the user annotates a fixture method with &lt;code&gt;@Time&lt;/code&gt;, they will get a nice error message from Spock that tells them that that is invalid.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s important to consider that there is guaranteed to only ever be &lt;strong&gt;one&lt;/strong&gt; instance of an extension for each spec. Spock will create an instance of your extension the first time it encounters your annotation, and then reuse that instance when it encounters later annotations (in the same spec).&lt;/p&gt;

&lt;h3&gt;Listening In&lt;/h3&gt;

&lt;p&gt;Spock has it&amp;#8217;s own execution listening API specified by &lt;code&gt;IRunListener&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;package org.spockframework.runtime;

import org.spockframework.runtime.extension.builtin.StepwiseExtension;
import org.spockframework.runtime.model.*;

public interface IRunListener {
  void beforeSpec(SpecInfo spec);
  void beforeFeature(FeatureInfo feature);
  void beforeIteration(IterationInfo iteration);
  void afterIteration(IterationInfo iteration);
  void afterFeature(FeatureInfo feature);
  void afterSpec(SpecInfo spec);
  void error(ErrorInfo error);
  void specSkipped(SpecInfo spec);
  void featureSkipped(FeatureInfo feature);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is all pretty straightforward, but you may be wondering about &lt;code&gt;beforeIteration()&lt;/code&gt; and &lt;code&gt;afterIteration()&lt;/code&gt;. This are for &lt;a href="http://pniederw.wordpress.com/2010/03/11/whats-new-in-spock-0-4-episode-1-data-tables/"&gt;parameterised (or data-driven)&lt;/a&gt; feature methods and are called for each set of parameters.&lt;/p&gt;

&lt;p&gt;Again, we have convenient super class to work with.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import org.spockframework.runtime.AbstractRunListener;
import org.spockframework.runtime.model.*;

class TimingRunListener extends AbstractRunListener {

  def timeSpec = false
  def specStartTime
  def featureStartTimes = [:]

  TimingRunListener(timeSpec, timedFeatures, timedFixtures) {
    this.timeSpec = timeSpec
    timedFeatures.each { featureTimes[it] = null }
  }

  private now() {
    System.currentTimeMillis()
  }

  private start(name) {
    println "starting $name …"
  }

  private done(name, started, finished = now()) {
    println "$name took ${finished - started} milliseconds"
  }

  void beforeSpec(SpecInfo spec) {
    if (timeSpec) {
      specStartTime = now()
      start("spec '$spec.name'")
    }
  }

  void beforeFeature(FeatureInfo feature) {
    if (featureStartTimes.containsKey(feature.name)) {
      featureStartTimes[feature.name] = now()
      start("feature '$feature.name'")
    }
  }

  void afterFeature(FeatureInfo feature) {
    def startedAt = featureStartTimes[feature.name]
    if (startedAt) {
      echo("feature '$feature.name'", startedAt)
    }
  }

  void afterSpec(SpecInfo spec) {
    if (specStartTime) {
      echo("spec '$spec.name'", specStartTime)
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our extension is now complete… let&amp;#8217;s try it out.&lt;/p&gt;

&lt;h2&gt;In Action&lt;/h2&gt;

&lt;p&gt;Now all we have to do is annotate our spec…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import spock.lang.*

@Time
class DoingStuff extends Specification {

  @Time
  def "a b c"() {
    when:
    Thread.sleep(1000)
    then:
    true
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we were to run this spec we would see something like…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;starting spec 'DoingStuff' …
starting feature 'a b c' …
feature 'a b c' took 1000 milliseconds
spec 'DoingStuff' took 1500 milliseconds
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Obviously the times are made up but you get the point.&lt;/p&gt;

&lt;h2&gt;The Real World&lt;/h2&gt;

&lt;p&gt;Spock ships with a bunch of extensions (as of today in 0.5-SNAPSHOT):&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;@AutoCleanup&lt;/code&gt; - allows a named cleaning up/closing method to be automatically called by Spock on a field &lt;/li&gt;
&lt;li&gt;&lt;code&gt;@FailsWith&lt;/code&gt; - makes a feature pass only if it raises a certain exception and it&amp;#8217;s uncaught&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@Ignore&lt;/code&gt; - prevents the feature or spec from running&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@IgnoreRest&lt;/code&gt; - prevents every other feature from running&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@RevertMetaClass&lt;/code&gt; - undoes any changes to the specified to meta classes of the specified classes during the feature (or spec)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@Stepwise&lt;/code&gt; - causes each feature method to be executed in declaration order and any after the first failure to be ignored (i.e. story mode)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@Timeout&lt;/code&gt; - causes a method to fail if it takes to long (and will interrupt it if it does take too long)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;For more info on any of these extensions, check out &lt;a href="http://code.google.com/p/spock/source/browse/#svn/trunk/spock-core/src/main/java/spock/lang"&gt;their javadoc comments&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You could very easily make your own extensions specific to your projects to make your life easier. You could load data fixtures, establish connections… all kinds of things.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;So that&amp;#8217;s “Annotation Driven Extensions” with the Spock Framework.&lt;/p&gt;

&lt;p&gt;Go forth and create some… and may the force be with you (wait… what?)&lt;/p&gt;</description><link>http://ldaley.com/post/971946675</link><guid>http://ldaley.com/post/971946675</guid><pubDate>Wed, 18 Aug 2010 22:58:07 +1000</pubDate><category>groovy spock</category></item><item><title>Proposal: Grails Plugin Collective</title><description>&lt;p&gt;The following is a proposal for, and a request for comment on, the idea of a semi-structured combination of social and technological systems and norms to initiate, develop and maintain Grails plugins.&lt;/p&gt;

&lt;h2&gt;The Problem Being Addressed&lt;/h2&gt;

&lt;p&gt;Typically, a plugin is born through inspiration or necessity. It&amp;#8217;s not uncommon that the original author at some point stops maintaining or developing a frequently-used or promising plugin. There are many reasons for this and they are in no way unique to the Grails ecosystem. People contribute and move on as is their want and well intentioned developers can quickly lose interest in developing a plugin due to roadblocks and lack of knowledge, experience and feedback.As a Software Developer using Grails professionally, the availability of a high quality plugin makes a significant product difference; and conversely an unsuccessful attempt to use a plugin due to bugs or lack of documentation costs real time. Often when finding an issue and fixing it, getting that fix back into the community takes considerable effort in coordinating with the plugin developer/maintainer who may or may not be around.&lt;/p&gt;

&lt;p&gt;As a plugin developer, during busy times it can be hard to keep up with bug reports, feature requests and Grails upgrades. It&amp;#8217;s also concerning that knowledge and understanding of the plugins I have authored rest largely with myself, creating a single point of failure. It would be much better if there were other people who could (and did) maintain and improve things in my (or any other author&amp;#8217;s) absence.&lt;/p&gt;

&lt;h2&gt;The Proposed Solution&lt;/h2&gt;

&lt;p&gt;To remedy this situation, I propose that a self-organised, distributed, democratic, collective be formed… to foster, develop and maintain Grails plugins. I am calling this idea the &amp;#8220;Grails Plugin Collective&amp;#8221; for the time being.&lt;/p&gt;

&lt;p&gt;The social structure is what would be the most interesting and, ultimately, enabling. It would allow members to work across plugins, scratching their own itches, and getting those fixes/features into release with minimal effort without risking quality. It would also enable steering and guiding the direction of plugins while allowing members to freely propose ideas and alternatives. Due to Grails&amp;#8217; “convention over configuration” nature, this becomes critically important. Hopefully, the collective wisdom of a group of individuals results in a highly consistent, conventional approach to how plugins work.&lt;/p&gt;

&lt;h3&gt;Goals and Aims&lt;/h3&gt;

&lt;ul&gt;&lt;li&gt;Create a community of volunteer skilled developers&lt;/li&gt;
&lt;li&gt;Support the recognition of official membership (primarily for CVs)&lt;/li&gt;
&lt;li&gt;Establish a set of useful, well used and high quality Grails plugins&lt;/li&gt;
&lt;li&gt;Encourage outside contributions, both one-off and in working towards membership&lt;/li&gt;
&lt;li&gt;Ensure adequate levels of documentation in a consistent format for all collectivised plugins&lt;/li&gt;
&lt;li&gt;Ensure proper quality control mechanisms such as code coverage and developer documentation&lt;/li&gt;
&lt;/ul&gt;&lt;h3&gt;Relationship with VMWare and certification&lt;/h3&gt;

&lt;p&gt;I propose that the collective should be an entity outside of VMWare. This does not exclude VMWare employees from participating in the collective by any means, or from having some kind of special role. It purely means that the entity is not bound to VMWare in any way other than through the licensing arrangement of any software owned by VMWare.&lt;/p&gt;

&lt;p&gt;I also propose that if a plugin certification scheme is ever established, it be done completely separately to the collective. I imagine that many of the collectivised plugins would aim for certification if at all possible, but in this respect they would be no different to other community plugins.&lt;/p&gt;

&lt;h3&gt;Procedures and Principles&lt;/h3&gt;

&lt;p&gt;The collective should aim to operate with the least amount of bureaucracy and procedure that is required. The core idea is that as a democratic structure, all proposals are put to a vote. Members will have a relatively short time frame (proposed: 48 hours) to vote. A certain proportion of the votes cast must be affirmative for the proposal to succeed. It&amp;#8217;s likely that there would also be some sort of veto mechanism for things that are extremely time critical.&lt;/p&gt;

&lt;p&gt;I image the following kinds of things would be voted on:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;API/Design questions &amp;amp; changes&lt;/li&gt;
&lt;li&gt;Releases&lt;/li&gt;
&lt;li&gt;Quality and process standards&lt;/li&gt;
&lt;li&gt;Developer membership&lt;/li&gt;
&lt;li&gt;Acceptance of new plugins&lt;/li&gt;
&lt;/ul&gt;&lt;h3&gt;Initial Membership&lt;/h3&gt;

&lt;p&gt;Being that what is being proposed is a self-organising, democratic social structure, I am hesitant to be to prescriptive about how such a thing might work in terms of my vision. I am interested in getting other people&amp;#8217;s ideas.&lt;/p&gt;

&lt;p&gt;An initial membership also needs to be put together. This will be somewhat of a challenge for a democratic outfit. To get the ball rolling, I suggest that the VMWare Grails team propose an initial membership of roughly 10 people (likely including themselves). From there, the collective can self organise and induct new members over time.&lt;/p&gt;

&lt;p&gt;So what are your thoughts? Is such an initiative worthwhile? Could it work? Could it succeed in raising and maintaining the quality of selected Grails plugins? Are there other such initiatives that we could learn from? What kind of social practices could be put in place to support rapid development while maintaining consistency and quality?&lt;/p&gt;

&lt;p&gt;Feel free to leave your opinion either here or on the grails-user mailing list.&lt;/p&gt;</description><link>http://ldaley.com/post/672832641</link><guid>http://ldaley.com/post/672832641</guid><pubDate>Mon, 07 Jun 2010 21:29:02 +1000</pubDate><category>software</category><category>grails</category></item><item><title>Putting the Artefact API to work in your Grails app</title><description>&lt;p&gt;I haven&amp;#8217;t seen many cases of people putting the Grails&amp;#8217; artefact API to use in their application. It&amp;#8217;s likely that most Grails&amp;#8217; users aren&amp;#8217;t aware that it exists, which in many ways is a good thing… it is after all an implementation concern.&lt;/p&gt;

&lt;p&gt;You can however put it to work in your own application.&lt;/p&gt;

&lt;h2&gt;What is it?&lt;/h2&gt;

&lt;p&gt;Perhaps it&amp;#8217;s best to discuss what an &lt;em&gt;artefact&lt;/em&gt; is in Grails first. An example of an artefact is a service &lt;em&gt;class&lt;/em&gt;. Think of what happens when your grails application starts; it finds all the service classes, creates an instance of each (typically) and autowires the dependencies. Grails defines a &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/commons/DefaultGrailsServiceClass.java" title="src/java/org/codehaus/groovy/grails/commons/DefaultGrailsServiceClass.java at master from grails's grails-core - GitHub"&gt;class whose instances represent a single service class&lt;/a&gt; and an &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/commons/ServiceArtefactHandler.java" title="src/java/org/codehaus/groovy/grails/commons/ServiceArtefactHandler.java at master from grails's grails-core - GitHub"&gt;associated handler&lt;/a&gt;. This is what I am collectively calling the Artefact API.&lt;/p&gt;

&lt;h2&gt;Why use it?&lt;/h2&gt;

&lt;p&gt;The biggest reason these days is by far the hot reloading support. That is, if you change an artefact class while the application is running, Grails (with some help from you) will reload the class and you get the changes without a restart. Of course, we are all familiar with this.&lt;/p&gt;

&lt;p&gt;There is a more subtle benefit though. You may have some kind of prominent &amp;amp; pervasive &lt;em&gt;concept&lt;/em&gt; in your application (like a &lt;em&gt;service&lt;/em&gt; is a concept). You might find that creating an artefact for this concept can make your life easier.&lt;/p&gt;

&lt;h2&gt;An example use case&lt;/h2&gt;

&lt;p&gt;Consider some kind of eStore, with a wide range of products. Our products have simple persistence requirements but can have wildly varying behaviours in the system, which are likely to get more complex over time. I try to avoid extensive subclassing of domain objects when the classes primarily vary in behaviour and not data. So we need to find another way to implement the varying behaviour.&lt;/p&gt;

&lt;h2&gt;The &lt;code&gt;ProductHandler&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Each product is going to provide a &lt;em&gt;handler&lt;/em&gt; (terrible name I know) that is responsible for the majority of the product&amp;#8217;s behaviour. Here is our product domain class…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class Product {
    String name
    
    // don't want to try and persist the handler
    static transients = ['handler'] 
    
    ProductHandler getHandler() {
        // somehow get the handler for this product
    }
}
&lt;/pre&gt;

&lt;p&gt;And we have a &lt;code&gt;ProductHandler&lt;/code&gt; interface for good measure…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
interface ProductHandler {
    void setProduct(Product)
    boolean isCanBeSold()
}}
&lt;/pre&gt;

&lt;h2&gt;A non artefact solution&lt;/h2&gt;

&lt;p&gt;One kind of traditional approach would be to have each product persist a key that refers to a particular product handler, and to have each product handler class register itself with some kind of registry.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class Product {
    String name
    String handlerKey
    
    def productHandlerService // autowired 
    
    // don't want to try and persist the handler
    static transients = ['handler']
    
    protected handler
    ProductHandler getHandler() {
        if (!handler) {
            handler = productHandlerService[this]
        }
        handler
    }
}

// Our registry
import grails.spring.BeanBuilder
class ProductHandlerService {
    def grailsApplication // autowired
    static private registry = [:].asSynchronized()
    
    static register(String key, Class handlerClass) {
        registry[key] = handlerClass // should check that handlerClass implements ProductHandler
    }
    
    protected createBeanBuilder() {
        new BeanBuilder(grailsApplication.mainContext, grailsApplication.classLoader)
    }
    
    protected instantiateHandler(handlerClass, Product product) {
        createBeanBuilder().with {
            beans {
                handler(handlerClass, product: product) {
                    // autowire the handler so it can use services etc.
                    it.autowire = true
                }
            }
            createApplicationContext().getBean('handler')
        }
    }
    
    def getAt(Product product) {
        def handlerClass = registry[product.handlerKey] // assume there is always a handler
        instantiateHandler(handlerClass, product)
    }
}

// Example Handler (in src/groovy dir)
class OnlyOnTuesdayProductHandler implements ProductHandler {
    static {
        ProductHandlerService.register('onlyOnTuesday', OnlyOnTuesdayProductHandler)
    }
    Product product
    boolean isCanBeSold() {
        new GregorianCalendar().get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY
    }
}
&lt;/pre&gt;

&lt;p&gt;This will get the job done (albeit in a cumbersome way), but it suffers from &lt;code&gt;ProductHandler&lt;/code&gt; implementations not being hot-reloadable.&lt;/p&gt;

&lt;h2&gt;Creating a &lt;code&gt;ProductHandler&lt;/code&gt; artefact&lt;/h2&gt;

&lt;p&gt;We can make things a bit easier &lt;strong&gt;and support hot reloading&lt;/strong&gt; by creating an artefact for product handlers.&lt;/p&gt;

&lt;p&gt;To do this we need a plugin…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class ProductHandlerGrailsPlugin {
    def version = "0.1"
    def grailsVersion = "1.2.* &amp;gt; *"
    
    // register the artefact handler
    def artefacts = [ProductHandlerArtefactHandler]
    
    // watch for any changes in these directories
    def watchedResources = [
        "file:./grails-app/productHandlers/**/*ProductHandler.groovy",
        "file:../../plugins/*/productHandlers/**/*ProductHandler.groovy"
    ]
    
    // Grails calls this when one of the files matching 'watchedResources' changes.
    // We have to actually swap in the new class when the source changes
    // There isn't anything special here, it's just boilerplate.
    def onChange = { event -&amp;gt;
        if (application.isArtefactOfType(ProductHandlerArtefactHandler.TYPE, event.source)) {
            def oldClass = application.getProductHandlerClass(event.source.name)
            application.addArtefact(ProductHandlerArtefactHandler.TYPE, event.source)

            // Reload subclasses
            application.productHandlerClasses.each {
                if (it.clazz != event.source &amp;amp;&amp;amp; oldClass.clazz.isAssignableFrom(it.clazz)) {
                    def newClass = application.classLoader.reloadClass(it.clazz.name)
                    application.addArtefact(ProductHandlerArtefactHandler.TYPE, newClass)
                }
            }
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;We also need a &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/commons/ArtefactHandler.java" title="src/java/org/codehaus/groovy/grails/commons/ArtefactHandler.java at master from grails's grails-core - GitHub"&gt;artefact handler&lt;/a&gt; &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/commons/ArtefactHandlerAdapter.java" title="src/java/org/codehaus/groovy/grails/commons/ArtefactHandlerAdapter.java at master from grails's grails-core - GitHub"&gt;implementation&lt;/a&gt; (which has to be in Java due to legacy reasons)…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.codehaus.groovy.grails.commons.ArtefactHandlerAdapter;

public class ProductHandlerArtefactHandler extends ArtefactHandlerAdapter {

    // the name for these artefacts in the application
    static public final String TYPE = "ProductHandler"; 

    // the suffix of all product handler classes (i.e. how they are identified as product handlers)
    static public final String SUFFIX = "ProductHandler"; 
    
    public ProductHandlerArtefactHandler() {
        super(TYPE, ProductHandlerClass.class, DefaultProductHandlerClass.class, SUFFIX);
    }
}
&lt;/pre&gt;

&lt;p&gt;And a &lt;code&gt;ProductHandlerClass&lt;/code&gt; interface (again in Java)…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.codehaus.groovy.grails.commons.GrailsClass;

public interface ProductHandlerClass extends GrailsClass {}
&lt;/pre&gt;

&lt;p&gt;And a &lt;code&gt;DefaultProductHandlerClass&lt;/code&gt; implementation of that interface (again in Java)…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.codehaus.groovy.grails.commons.AbstractGrailsClass;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
 
public class DefaultProductHandlerClass extends AbstractGrailsClass implements ProductHandlerClass {

    public DefaultProductHandlerClass(Class clazz) {
        super(clazz, ProductHandlerArtefactHandler.SUFFIX);
    }
    
    // This method will get the static property 'key' on the underlying 
    // ProductHandler class that it represents.
    public String getKey() { 
        Object key = GrailsClassUtils.getStaticPropertyValue(getClazz(), "key");
        if (key == null) {
            return null;
        } else {
            return key.toString();
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s a shotgun intro to the Grails Artefact API classes like &lt;code&gt;GrailsClass&lt;/code&gt; and &lt;code&gt;ArtefactHandlerAdapter&lt;/code&gt; just covering the stuff we need. Check out the linked to source for deeper detail.&lt;/p&gt;

&lt;p&gt;Here is what we have done…&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Create a plugin that registers an artefact handler for product handlers&lt;/li&gt;
&lt;li&gt;Register for changes to source in &lt;code&gt;grails-app/productHandlers&lt;/code&gt; in the app and plugins&lt;/li&gt;
&lt;li&gt;Provide an &lt;code&gt;onChange&lt;/code&gt; handler that reloads product handler classes when they change&lt;/li&gt;
&lt;li&gt;Provide an &lt;code&gt;ArtefactHandler&lt;/code&gt; implementation that specifies &lt;em&gt;what&lt;/em&gt; a product handler class is&lt;/li&gt;
&lt;li&gt;Provide a &lt;code&gt;GrailsClass&lt;/code&gt; subinterface for product handler classes&lt;/li&gt;
&lt;li&gt;Provide an implementation of that interface that returns the static property &lt;code&gt;key&lt;/code&gt; on the underlying class (among other things)&lt;/li&gt;
&lt;/ol&gt;&lt;h2&gt;Putting it together&lt;/h2&gt;

&lt;p&gt;Armed with our new artefact, we can now simplify our initial implementation…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
// Our registry
import grails.spring.BeanBuilder
class ProductHandlerService {
    def grailsApplication // autowired
    
    protected createBeanBuilder() {
        new BeanBuilder(grailsApplication.mainContext, grailsApplication.classLoader)
    }
    
    protected instantiateHandler(handlerClass, Product product) {
        createBeanBuilder().with {
            beans {
                handler(handlerClass, product: product) {
                    // autowire the handler so it can use services etc.
                    it.autowire = true
                }
            }
            createApplicationContext().getBean('handler')
        }
    }
    
    def getAt(Product product) {
        def productHandlerClasses = grailsApplication.productHandlerClasses // a list of DefaultProductHandlerClass
        def handlerClass = productHandlerClasses.find { it.key == product.handlerKey } // find the one with the matching key
        instantiateHandler(handlerClass, product)
    }
}

// Example Handler (in grails-app/productHandlers dir)
class OnlyOnTuesdayProductHandler implements ProductHandler {
    static key = 'onlyOnTuesday'
    Product product
    boolean isCanBeSold() {
        new GregorianCalendar().get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY
    }
}
&lt;/pre&gt;

&lt;h2&gt;Being more conventional&lt;/h2&gt;

&lt;p&gt;Each of our product handler classes must specify a &lt;code&gt;key&lt;/code&gt;, that products use to link themselves to a particular handler implementation. You could do away with this, and infer the key from the class name quite easily.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class ProductHandlerService {
    // …snip…
    
    def getAt(Product product) {
        def handlerClass = grailsApplication.getProductHandlerClass(product.handlerKey)
        instantiateHandler(handlerClass, product)
    }
}
&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;grailsApplication.getProductHandlerClass()&lt;/code&gt; method given the value &lt;code&gt;"onlyOnTuesday"&lt;/code&gt; would return the &lt;code&gt;OnlyOnTuesdayProductHandler&lt;/code&gt; class object.&lt;/p&gt;

&lt;p&gt;In this particular case I personally wouldn&amp;#8217;t do this as every time I renamed a product handler class I would have to update the products that use that handler in the DB, but other situations may not have this issue.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;All product handler classes are now reloadable, which would obviously be a substantial productivity boost, without all that much work on our part. This approach could be used for any kind of &lt;em&gt;concept&lt;/em&gt; or set of classes in your application that don&amp;#8217;t fit into the standard controller, service, taglib etc. pattern.&lt;/p&gt;

&lt;p&gt;The Artefact API can seem a bit confusing if you don&amp;#8217;t take into consideration that this was the heart of Grails in the early days. It&amp;#8217;s still there and is used by a great many plugins (e.g. grails-quartz) as well as being used extensively internally in Grails, but it doesn&amp;#8217;t quite have the same role that it used to.&lt;/p&gt;

&lt;p&gt;Hopefully this has shown you how you can, and why you might want to, use the artefact API internally in your applications.&lt;/p&gt;</description><link>http://ldaley.com/post/653190105</link><guid>http://ldaley.com/post/653190105</guid><pubDate>Tue, 01 Jun 2010 22:42:00 +1000</pubDate><category>software</category><category>grails</category></item><item><title>Forwarding/Chaining and models in Grails</title><description>&lt;p&gt;I recently hit the case where I need to forward a request in Grails to a second action, but that action needed access to the &lt;em&gt;model&lt;/em&gt; generated by the first (note that this is different to params). The &lt;a href="http://grails.org/doc/latest/ref/Controllers/forward.html" title="Grails Reference"&gt;Grails documentation doesn&amp;#8217;t mention the ability to pass models when forwarding at all&lt;/a&gt;, but if you &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/web/metaclass/ForwardMethod.groovy#L61" title="src/java/org/codehaus/groovy/grails/web/metaclass/ForwardMethod.groovy at master from grails's grails-core - GitHub"&gt;check the source code you can see that the capability is there&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;What&amp;#8217;s also missing is how to access the existing model in a forwarded to or chained to action. If you trace the code, you see that the model eventually gets passed to Spring&amp;#8217;s [&lt;code&gt;WebUtils.exposeRequestAttributes()&lt;/code&gt;](&lt;a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/util/WebUtils.html#exposeRequestAttributes"&gt;http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/util/WebUtils.html#exposeRequestAttributes&lt;/a&gt;(javax.servlet.ServletRequest, java.util.Map)) method, that simply makes each item in the model a request attribute. So in Grails you can access them via the request variable…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class MyController {
    
    def first = {
        forward(action: 'second', model: [thing: "thing"])
    }
    
    def second = {
        assert request.thing == "thing"
        // go forth and do stuff
    }
    
}
&lt;/pre&gt;

&lt;h3&gt;Why use model instead of params?&lt;/h3&gt;

&lt;p&gt;Params can &lt;em&gt;only&lt;/em&gt; be strings where as you can pass any type via the model.&lt;/p&gt;</description><link>http://ldaley.com/post/627158024</link><guid>http://ldaley.com/post/627158024</guid><pubDate>Mon, 24 May 2010 14:35:25 +1000</pubDate><category>software</category><category>grails</category></item><item><title>Custom Grails Test Types/Phases</title><description>&lt;p&gt;Recently there was a &lt;a href="http://grails.1312388.n4.nabble.com/Running-some-tests-in-a-separate-test-suite-td2075869.html#a2075869" title="Nabble - Grails - user - Running some tests in a separate test suite"&gt;query on the grails-user mailing list&lt;/a&gt; asking how to create a separate test &lt;em&gt;suite&lt;/em&gt; (in the poster&amp;#8217;s terminology). In Grails&amp;#8217; terminology, what the poster wanted was a separate test &lt;em&gt;type&lt;/em&gt; that could be run separately.&lt;/p&gt;

&lt;p&gt;The following is an expansion on the solution offered in the thread.&lt;/p&gt;

&lt;p&gt;There are two core concepts in the test system; &lt;em&gt;types&lt;/em&gt; and &lt;em&gt;phases&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;Test Phases&lt;/h2&gt;

&lt;p&gt;A test &lt;em&gt;phase&lt;/em&gt; refers to the state of the application at test time. Grails comes with 4…&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;code&gt;Unit&lt;/code&gt; - no application state, only the classpath is configured&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Integration&lt;/code&gt; - application running (e.g. database, beans), but not listening for http requests&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Functional&lt;/code&gt; - application is fully running&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Other&lt;/code&gt; - same as &lt;code&gt;Unit&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Here&amp;#8217;s how to create your own test phase.&lt;/p&gt;

&lt;p&gt;In your &lt;code&gt;scripts/_Events.groovy&lt;/code&gt; file…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
// 1. add the name of your phase to this variable with this event handler
eventAllTestsStart = {
    phasesToRun &amp;lt;&amp;lt; "custom"
}

// 2. Create a «phase name»Tests variable containing a list of test types (more on this later)
customTests = ["custom"]

// 3. Create pre and post closures
customTestPhasePreparation = {
    // called at the start of the phase
}
customTestPhaseCleanUp = {
    // called at the end of the phase
}
&lt;/pre&gt;

&lt;p&gt;Even if you don&amp;#8217;t have anything to do in your &lt;code&gt;Preparation&lt;/code&gt; and &lt;code&gt;CleanUp&lt;/code&gt; closures, you still need to create empty ones.&lt;/p&gt;

&lt;p&gt;Note that the name of a test phase has no real correlation to it&amp;#8217;s type&amp;#8217;s names. In this example we just happen to have a type with name &lt;code&gt;custom&lt;/code&gt; in a phase named &lt;code&gt;custom&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Mimicking standard phases&lt;/h3&gt;

&lt;p&gt;If you need your phase to be like one of the standard phases, just call that phase&amp;#8217;s handlers…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
customTestPhasePreparation = {
    integrationTestPhasePreparation()
}
customTestPhaseCleanUp = {
    integrationTestPhaseCleanUp()
}
&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s all there is to it.&lt;/p&gt;

&lt;h2&gt;Test Types&lt;/h2&gt;

&lt;p&gt;A test &lt;em&gt;type&lt;/em&gt; is really two things; a grouping of tests and a test &lt;em&gt;running&lt;/em&gt; mechanism.&lt;/p&gt;

&lt;p&gt;Above we had…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
…
// 2. Create a «phase name»Tests variable containing a list of test types (more on this later)
customTests = ["custom"]
…
&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;«phaseName»Tests&lt;/code&gt; lists contains a phase&amp;#8217;s test types. These must either be &lt;code&gt;String&lt;/code&gt;&amp;#8217;s or instance of &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/test/GrailsTestType.groovy" title="src/java/org/codehaus/groovy/grails/test/GrailsTestType.groovy at master from grails's grails-core - GitHub"&gt;&lt;code&gt;GrailsTestType&lt;/code&gt;&lt;/a&gt;. Writing a &lt;code&gt;GrailsTestType&lt;/code&gt; implementation will be the subject of a future article (if you are interested, start with the JavaDoc on &lt;code&gt;GrailsTestType&lt;/code&gt; and then look at implementations in the wild like the one from the Spock plugin).&lt;/p&gt;

&lt;p&gt;Grails ships with the &lt;a href="http://github.com/grails/grails-core/blob/master/src/java/org/codehaus/groovy/grails/test/junit4/JUnit4GrailsTestType.groovy" title="src/java/org/codehaus/groovy/grails/test/junit4/JUnit4GrailsTestType.groovy at master from grails's grails-core - GitHub"&gt;JUnit4GrailsTestType&lt;/a&gt; which is what &lt;code&gt;String&lt;/code&gt;s get implicitly converted to (this happens &lt;a href="http://github.com/grails/grails-core/blob/master/scripts/_GrailsTest.groovy#L128" title="scripts/_GrailsTest.groovy at master from grails's grails-core - GitHub"&gt;here&lt;/a&gt;) for both convenience and legacy reasons.&lt;/p&gt;

&lt;p&gt;Test types are associated to a certain directory (under &lt;code&gt;test&lt;/code&gt;) and one or more class name suffixes. The JUnit test type uses the suffix &lt;code&gt;Tests&lt;/code&gt; pre Grails 1.3 and &lt;code&gt;Tests&lt;/code&gt; and &lt;code&gt;Test&lt;/code&gt; in Grails 1.3. The directory for &lt;code&gt;String&lt;/code&gt; test types is the value (i.e. &lt;code&gt;test/custom&lt;/code&gt; for our above example).&lt;/p&gt;

&lt;h3&gt;Pre and post test type handlers&lt;/h3&gt;

&lt;p&gt;You don&amp;#8217;t &lt;em&gt;need&lt;/em&gt; to write pre/post handlers for types like you do with phases. But should you need to, here is how you do it…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
eventTestSuiteStart = { typeName -&amp;gt;
    if (typeName == 'custom') {
        // do stuff
    }
}

eventTestSuiteEnd = { typeName -&amp;gt;
    if (typeName == 'custom') {
        // do stuff
    }
}
&lt;/pre&gt;

&lt;p&gt;The event has that name due to legacy reasons.&lt;/p&gt;

&lt;h3&gt;Types in integration or functional phases&lt;/h3&gt;

&lt;p&gt;Above we created an integration-like phase called &lt;code&gt;custom&lt;/code&gt;. Without a bit of extra work, our tests won&amp;#8217;t be completely like standard integration tests in that they won&amp;#8217;t have transaction rollback and other bits and pieces. To do this you need to register a &lt;code&gt;JUnit4GrailsTestType&lt;/code&gt; so it can be configured. Here is a complete example on how you would do this…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.codehaus.groovy.grails.test.junit4.JUnit4GrailsTestType

// 1. add the name of your phase to this variable with this event handler
eventAllTestsStart = {
    phasesToRun &amp;lt;&amp;lt; "custom"
}

// 2. Create a custom test type
def testTypeName = "custom"
def testDirectory = "custom"
def testMode = new GrailsTestMode(autowire: true, wrapInTransaction: true, wrapInRequestEnvironment: true)
def customTestType = new JUnit4GrailsTestType(testTypeName, testDirectory, testMode)

// 3. Create a «phase name»Tests variable containing the test type(s)
customTests = [customTestType]

// 4. Create pre and post closures
customTestPhasePreparation = {
    integrationTestPhasePreparation()
}
customTestPhaseCleanUp = {
    integrationTestPhaseCleanUp()
}
&lt;/pre&gt;

&lt;p&gt;For a functional-like phase you would do…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.codehaus.groovy.grails.test.junit4.JUnit4GrailsTestType

// 1. add the name of your phase to this variable with this event handler
eventAllTestsStart = {
    phasesToRun &amp;lt;&amp;lt; "custom"
}

// 2. Create a custom test type
def testTypeName = "custom"
def testDirectory = "custom"
def testMode = new GrailsTestMode(autowire: true)
def customTestType = new JUnit4GrailsTestType(testTypeName, testDirectory, testMode)

// 3. Create a «phase name»Tests variable containing the test type(s)
customTests = [customTestType]

// 4. Create pre and post closures
customTestPhasePreparation = {
    functionalTestPhasePreparation()
}
customTestPhaseCleanUp = {
    functionalTestPhaseCleanUp()
}
&lt;/pre&gt;

&lt;p&gt;(functional tests don&amp;#8217;t need rollback transactions or fake request environments)&lt;/p&gt;

&lt;p&gt;For completeness, here&amp;#8217;s a unit-like phase (though you could just use a &lt;code&gt;String&lt;/code&gt;)…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.codehaus.groovy.grails.test.junit4.JUnit4GrailsTestType

// 1. add the name of your phase to this variable with this event handler
eventAllTestsStart = {
    phasesToRun &amp;lt;&amp;lt; "custom"
}

// 2. Create a custom test type
def testTypeName = "custom"
def testDirectory = "custom"
def customTestType = new JUnit4GrailsTestType(testTypeName, testDirectory)

// 3. Create a «phase name»Tests variable containing the test type(s)
customTests = [customTestType]

// 4. Create pre and post closures
customTestPhasePreparation = {
    unitTestPhasePreparation()
}
customTestPhaseCleanUp = {
    unitTestPhaseCleanUp()
}
&lt;/pre&gt;

&lt;h2&gt;Running your phase/type&lt;/h2&gt;

&lt;p&gt;Once registered and configured, your custom tests can be run just like any other tests using &lt;code&gt;grails test-app&lt;/code&gt;. You can even target them like normal…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;grails test-app custom: // run all types in the custom phase
grails test-app :custom // run the custom type in all phases
grails test-app custom:custom // run the custom type in the custom phase
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can even target tests and test methods&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;grails test-app custom:custom Person* Product.testSave
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above example would run all test classes starting with &lt;code&gt;Person&lt;/code&gt; (and ending in &lt;code&gt;Test&lt;/code&gt; or &lt;code&gt;Tests&lt;/code&gt;) and the &lt;code&gt;testSave&lt;/code&gt; test in &lt;code&gt;ProductTest&lt;/code&gt; or &lt;code&gt;ProductTests&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The Grails manual has a &lt;a href="http://www.grails.org/doc/latest/guide/9.%20Testing.html" title="9. Testing"&gt;section on running tests&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Not having your type run by default&lt;/h2&gt;

&lt;p&gt;The original email query was asking for a solution for having a test type that didn&amp;#8217;t run with &lt;code&gt;grails test-app&lt;/code&gt;, but ran when explicitly requested. Given the above, the following should make sense…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
eventAllTestsStart = { 
    if (testOptions.customOnly) { 
        phasesToRun = ["integration"] // remove the other phases 
        integrationTests = [] // remove the normal integration  tests 
        addCustomTestType() 
    } else if (testOptions.withCustom) { 
        addCustomTestType() 
    } 
} 

addCustomTestType = { 
        integrationTests &amp;lt;&amp;lt; "ipbx"
}
&lt;/pre&gt;

&lt;p&gt;(The &lt;code&gt;testOptions&lt;/code&gt; map contains all switch or parameter style arguments passed to &lt;code&gt;grails test-app&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;So this gives us…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;grails test-app // don't run the custom type
grails test-app -only-custom // run ONLY the custom type
grails test-app -with-custom // run ALL types including our custom type
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Why isn&amp;#8217;t this in the manual?&lt;/h2&gt;

&lt;p&gt;Laziness on my part. This article will likely be the basis of what will end up in the manual (&lt;a href="http://jira.codehaus.org/browse/GRAILS-6301" title="[#GRAILS-6301] Add documentation on advanced testing concepts (e.g. adding new custom test types) - jira.codehaus.org"&gt;GRAILS-6301&lt;/a&gt;).&lt;/p&gt;</description><link>http://ldaley.com/post/615966534</link><guid>http://ldaley.com/post/615966534</guid><pubDate>Thu, 20 May 2010 21:21:04 +1000</pubDate><category>software</category><category>grails</category><category>testing</category></item><item><title>Grails, WebTest and JQuery.</title><description>&lt;p&gt;The recently released &lt;a href="http://grails.org/plugin/webtest" title="Grails Plugin - Webtest Plugin"&gt;grails-webtest 2.0.2&lt;/a&gt; now installs &lt;a href="http://webtest.canoo.com" title="Canoo WebTest"&gt;WebTest&lt;/a&gt;  via &lt;a href="http://grails.org/doc/latest/guide/3.%20Configuration.html#3.7%20Dependency%20Resolution" title="3. Configuration"&gt;dependency resolution&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This allows you to work around the &lt;a href="http://old.nabble.com/Problem-with-jQuery-and-HtmlUnit-2.4-td21931584.html" title="Old Nabble - HtmlUnit - General - Problem with jQuery and HtmlUnit 2.4"&gt;HTMLUnit 2.4 incompatibility with JQuery&lt;/a&gt;. WebTest 3.0 depends on HTMLUnit 2.4, but we can force the use of HTMLUnit 2.5 which works with JQuery.&lt;/p&gt;

&lt;p&gt;Simply add it as a dependency in your app.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
grails.project.dependency.resolution = {
    inherits "global"
    log "warn"

    repositories {
        grailsHome()
        mavenCentral()
    }
  
    dependencies {
        test('net.sourceforge.htmlunit:htmlunit:2.5') {
            excludes 'xalan' // IVY-1006 - use xalan 2.7.0 to avoid (see below)
            excludes 'xml-apis' // GROOVY-3356
        }
        test('xalan:xalan:2.7.0') {
            excludes 'xml-apis' // GROOVY-3356
        }
    }
}    
&lt;/pre&gt;</description><link>http://ldaley.com/post/440451067</link><guid>http://ldaley.com/post/440451067</guid><pubDate>Thu, 11 Mar 2010 15:16:30 +1100</pubDate><category>software</category><category>grails</category></item><item><title>Scoped Services &amp; Proxies in Grails</title><description>&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; I have released a &lt;a href="http://github.com/alkemist/grails-scoped-proxy"&gt;plugin&lt;/a&gt; that makes working with scoped proxies a little bit easier.&lt;/p&gt;

&lt;p&gt;Grails has supported &lt;a href="http://www.grails.org/doc/latest/guide/8.%20The%20Service%20Layer.html#8.2%20Scoped%20Services" title="8. The Service Layer"&gt;“scoping” services&lt;/a&gt; for as long as I have been working with it. Surprisingly, you very rarely here of people using this feature. For my money, it&amp;#8217;s one of the lowest cost techniques available to avoid the inherent spaghetti in referencing the &lt;code&gt;session&lt;/code&gt; and &lt;code&gt;request&lt;/code&gt; (for all intents and purposes) global objects.&lt;/p&gt;

&lt;p&gt;This feature is built on top of &lt;a href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes" title="Chapter 3. The IoC container"&gt;Spring&amp;#8217;s bean scoping&lt;/a&gt;. However, you don&amp;#8217;t need to know much Spring to get value out of this in Grails.&lt;/p&gt;

&lt;p&gt;Scoping a service is as simple as declaring a static &lt;code&gt;scope&lt;/code&gt; property with the name of the desired scope…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class MyScopedService {
    static scope = 'session'
}
&lt;/pre&gt;

&lt;p&gt;So now, for each distinct session there will be a distinct instance of &lt;code&gt;MyScopedService&lt;/code&gt; in our application.&lt;/p&gt;

&lt;h2&gt;A shopping cart as a service&lt;/h2&gt;

&lt;p&gt;An easy to understand use case for this might be a shopping cart…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class CartService {
    static scope = 'session'
    
    
    void addCartItem(cartItem) {
        // …
    }
    
    def getPrice() {
        // …
    }
}
&lt;/pre&gt;

&lt;p&gt;We would use this in our controller like so…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class CartController {
    
    def cartService
    
    def addItem = {
        cartService.addItem(/* cart item */)
    }
    
    def price = {
        println "Cart price is: " + cartService.price
    }
}
&lt;/pre&gt;

&lt;p&gt;You might be wondering just which session that &lt;code&gt;cartService&lt;/code&gt; belongs to. Grails controllers are &lt;em&gt;prototype&lt;/em&gt; scoped beans (which means a new one is created whenever it is retrieved from the application context) and only ever created inside of a request environment. Therefore, a Grails controller always lives within the context of a session. So when the controller instance is created by Grails at the start of the request, it can be injected with the instance of &lt;code&gt;cartService&lt;/code&gt; that correlates to the session that the request is for.&lt;/p&gt;

&lt;p&gt;But what about objects that don&amp;#8217;t live inside a request (like taglibs)? For that we need a scoped proxy.&lt;/p&gt;

&lt;h2&gt;Using proxies to deal with scope differences&lt;/h2&gt;

&lt;p&gt;So we want to have a taglib that renders the current price of the shopping cart. We could pass the &lt;code&gt;cartService&lt;/code&gt; instance to the view layer via our controller action and then pass it to the taglib, but that gets tiresome &lt;em&gt;real&lt;/em&gt; quick when you start doing it for lots of actions. Since our cart is now a Spring managed bean we could try adding it as a dependency of our taglib…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class CartTagLib {
    
    def cartService
    
    def price = {
        out &amp;lt;&amp;lt; cartService.price
    }
}
&lt;/pre&gt;

&lt;p&gt;If you try and do this you are going to get…&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cartService': Scope 'session' is not active for the current thread;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Grails taglibs are &lt;code&gt;singleton&lt;/code&gt; scoped so are created at application startup when the notion of &lt;code&gt;session&lt;/code&gt; doesn&amp;#8217;t make any sense. What we can do though is create a singleton &lt;em&gt;proxy&lt;/em&gt; that &lt;em&gt;delegates&lt;/em&gt; to the relevant &lt;code&gt;cartService&lt;/code&gt; object at execution time (taglibs are always executed during a request so there will be session when the tag is executed).&lt;/p&gt;

&lt;p&gt;With Grails 1.2 and earlier, we have to create this proxy manually by adding this to &lt;code&gt;grails-app/conf/resources.groovy&lt;/code&gt;…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.springframework.aop.scope.ScopedProxyFactoryBean

beans = {
    cartServiceProxy(ScopedProxyFactoryBean) {
        targetBeanName = 'cartService'
        proxyTargetClass = true
    }
}
&lt;/pre&gt;

&lt;p&gt;This, in effect, creates a singleton bean, which is a dynamically generated subclass of &lt;code&gt;CartService&lt;/code&gt;, that delegates method/property calls to the &lt;code&gt;cartService&lt;/code&gt; instance stored in the session. Check out &lt;a href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes-other-injection" title="Chapter 3. The IoC container"&gt;Spring&amp;#8217;s docs on scope proxies&lt;/a&gt; if you want more information on this.&lt;/p&gt;

&lt;p&gt;Now we just rewrite our taglib to use our proxy…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class CartTagLib {
    
    def cartServiceProxy
    
    def price = {
        out &amp;lt;&amp;lt; cartServiceProxy.price
    }
}
&lt;/pre&gt;

&lt;p&gt;You can now use your &lt;code&gt;cartServiceProxy&lt;/code&gt; anywhere like other services or filters. As long as the code that calls &lt;code&gt;cartServiceProxy&lt;/code&gt; is executed in a request environment everything will work as expected in a completely thread safe manner.&lt;/p&gt;

&lt;h3&gt;Some notes on Grails 1.3 improvements&lt;/h3&gt;

&lt;p&gt;Grails 1.3 will make scoped beans even more attractive by removing the need to define your own proxies. All you will have to do is…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
class CartService {
    static scope = 'session'
    static proxy = true
}
&lt;/pre&gt;

&lt;p&gt;To have a proxy named &lt;code&gt;cartServiceProxy&lt;/code&gt; created for you. You can &lt;a href="http://jira.codehaus.org/browse/GRAILS-5701"&gt;track this new feature&lt;/a&gt; via the Grails issue tracker.&lt;/p&gt;

&lt;p&gt;Grails 1.3 will also &lt;a href="http://jira.codehaus.org/browse/GRAILS-5911"&gt;support scoped tag libs&lt;/a&gt; in the same manner as services.&lt;/p&gt;

&lt;h2&gt;Testing and scoped services&lt;/h2&gt;

&lt;p&gt;When integration testing scoped services, you need to be aware of the request/session lifecycle semantics.&lt;/p&gt;

&lt;p&gt;Each test method is run in it&amp;#8217;s own unique environment. This means two things; you must use a proxy to access a request or session scoped in a test, and each test method will have it&amp;#8217;s own distinct underlying service instance.&lt;/p&gt;

&lt;p&gt;class SomeTests extends GroovyTestCase {&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import grails.plugin.spock.*

class ScopedServiceSpec extends IntegrationSpec {
 
    def sessionScopedServiceProxy
    def requestScopedServiceProxy
    
    void test1() {
        expect:
        sessionScopedServiceProxy.property == null
        requestScopedServiceProxy.property == null
        when:
        sessionScopedServiceProxy.property = 1
        requestScopedServiceProxy.property = 1
        then:
        sessionScopedServiceProxy.property == 1
        requestScopedServiceProxy.property == 1
    }

    void test2() {
        expect:
        sessionScopedServiceProxy.property == null
        requestScopedServiceProxy.property == null
        when:
        sessionScopedServiceProxy.property = 2
        requestScopedServiceProxy.property = 2
        then:
        sessionScopedServiceProxy.property == 2
        requestScopedServiceProxy.property == 2
    }
}
&lt;/pre&gt;

&lt;h2&gt;Why use scoped services and proxies?&lt;/h2&gt;

&lt;p&gt;For me it&amp;#8217;s really about expressing intent. Some aspects of your application, like a shopping cart, are so pervasive that they end up everywhere in your code. It&amp;#8217;s very hard to track down who is getting something from or setting something in the &lt;code&gt;session&lt;/code&gt; or &lt;code&gt;request&lt;/code&gt; objects in controllers, taglibs or filters. If you use scoped services, it&amp;#8217;s &lt;em&gt;very&lt;/em&gt; easy to see who is doing what. I can tell a controller does something with the cart because I see &lt;code&gt;def cartService&lt;/code&gt; at the start of the class. That&amp;#8217;s easier to spot than &lt;code&gt;session.cart&lt;/code&gt; buried in an action. I also find it allows me to stay more focussed in the language of my problem domain.&lt;/p&gt;

&lt;p&gt;Scoped services are a great tool to have in your arsenal. In an upcoming post, I&amp;#8217;ll be discussing using custom scopes or lifecycles for your scoped services.&lt;/p&gt;</description><link>http://ldaley.com/post/436635056</link><guid>http://ldaley.com/post/436635056</guid><pubDate>Tue, 09 Mar 2010 21:46:00 +1100</pubDate><category>software</category><category>grails</category></item><item><title>Configuration based Spring bean definition with Grails. </title><description>&lt;p&gt;I released a new version of the Grails JMS plugin (0.5) over the weekend. This release features completely rewritten internals to expose every configuration aspect of the underlying Spring JMS classes. JMS is a complicated topic with lots of setup and configuration options so this level of access is necessary.&lt;/p&gt;

&lt;p&gt;What&amp;#8217;s novel about the approach is that it allows users to configure the underlying beans via the Grails application config, rather than via direct Spring bean configuration. This has the advantage of being more generally accessible as a lot of Grails developers still shy away from directly configuring beans. It also has the advantage of allowing the plugin to assert a certain level of control over the bean definitions.&lt;/p&gt;

&lt;h2&gt;A little bit about Grails JMS&lt;/h2&gt;

&lt;p&gt;The plugin makes it convenient to specify service methods as JMS listeners.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import grails.plugin.jms.Subscriber

class ListeningService {
    
    @Subscriber
    void interestingStuff(payload) {
        
    }
    
}
&lt;/pre&gt;

&lt;p&gt;Whenever a message is sent to the topic &amp;#8220;interestingStuff&amp;#8221;, the message will be delivered to this service method.&lt;/p&gt;

&lt;p&gt;There are two aspects to receiving JMS messages with Spring&amp;#8217;s JMS support; &lt;a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/jms/listener/DefaultMessageListenerContainer.html" title="DefaultMessageListenerContainer"&gt;containers&lt;/a&gt; and &lt;a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/jms/listener/adapter/MessageListenerAdapter.html" title="MessageListenerAdapter"&gt;adapters&lt;/a&gt;. For each listener there is a distinct container and adapter pair. In a plain Spring app, you would configure a pair of these beans to receive your messages. If you have a look at those classes, there are a lot of config options. The goal of this plugin  release was to give you access to those options &lt;em&gt;should you need it&lt;/em&gt;, but not force you to define everything yourself.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;@Subscriber&lt;/code&gt; annotation has &lt;code&gt;container&lt;/code&gt; and &lt;code&gt;adapter&lt;/code&gt; parameters that default to &lt;code&gt;"standard"&lt;/code&gt;. These parameters are the names of the &lt;em&gt;abstract&lt;/em&gt; beans that the concrete listener and adapter instances shall inherit from. There are implicit suffixes though; a &lt;code&gt;container&lt;/code&gt; value of &lt;code&gt;"standard"&lt;/code&gt; actually means the bean &lt;code&gt;standardJmsListenerContainer&lt;/code&gt; and so forth. The plugin does force some properties on the concrete instances, but very few. The majority of configuration is controlled by the abstract base.&lt;/p&gt;

&lt;h2&gt;Config based bean definitions&lt;/h2&gt;

&lt;p&gt;The other half of the story is how the beans are defined based on the config. This is driven by the &lt;a href="http://github.com/alkemist/grails-jms/blob/master/src/groovy/grails/plugin/jms/bean/MapBasedBeanDefinitionBuilder.groovy" title="src/groovy/grails/plugin/jms/bean/MapBasedBeanDefinitionBuilder.groovy at master from alkemist's grails-jms - GitHub"&gt;MapBasedBeanDefinitionBuilder&lt;/a&gt; that takes a name and &lt;code&gt;Map&lt;/code&gt; of properties a certain format and registers a bean based on the map data. There are also certain MapBasedBeanDefinitionBuilder subclasses in the plugin like &lt;a href="http://github.com/alkemist/grails-jms/blob/master/src/groovy/grails/plugin/jms/bean/JmsListenerContainerAbstractBeanDefinitionBuilder.groovy" title="src/groovy/grails/plugin/jms/bean/JmsListenerContainerAbstractBeanDefinitionBuilder.groovy at master from alkemist's grails-jms - GitHub"&gt;JmsListenerContainerAbstractBeanDefinitionBuilder&lt;/a&gt; that specialise in creating certain types of beans.&lt;/p&gt;

&lt;p&gt;The default set of beans configurations look like this&amp;#8230;&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import org.springframework.jms.support.converter.SimpleMessageConverter
import org.springframework.jms.listener.DefaultMessageListenerContainer

templates {
    standard {
        connectionFactoryBean = "jmsConnectionFactory"
        messageConverter = new SimpleMessageConverter()
    }
}
containers {
    standard {
        concurrentConsumers = 1
        subscriptionDurable = false
        autoStartup = false
        connectionFactoryBean = "jmsConnectionFactory"
        messageSelector = null
        cacheLevel = DefaultMessageListenerContainer.CACHE_SESSION
    }
}
adapters {
    standard {
        messageConverter = new SimpleMessageConverter()
        persistenceInterceptorBean = 'persistenceInterceptor'
    }
}
&lt;/pre&gt;

&lt;p&gt;The details aren&amp;#8217;t important. The point is to illustrate the syntax.&lt;/p&gt;

&lt;h2&gt;Overriding defaults&lt;/h2&gt;

&lt;p&gt;This default config gets merged with the application config under the &lt;code&gt;jms&lt;/code&gt; key (e.g. &lt;code&gt;grailsApplication.config.jms&lt;/code&gt;). So to override the standard container to use a different connection factory we would have the following in our &lt;code&gt;Config.groovy&lt;/code&gt;&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
jms {
    containers {
        standard {
            connectionFactoryBean = "someOtherJmsConnectionFactory"
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;Because &lt;code&gt;Config.groovy&lt;/code&gt; is environment aware, we can also do things like&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
environments {
    development {
        jms.containers.standard.connectionFactoryBean = "someOtherJmsConnectionFactory"
    }
    test {
        jms.containers.standard.connectionFactoryBean = "testJmsConnectionFactory"
    }
}
&lt;/pre&gt;

&lt;p&gt;You could even change the class of the default container definition.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
jms {
    containers {
        standard {
            meta {
                clazz = SomeOtherListenerContainer
            }
        }
    }
}
&lt;/pre&gt;

&lt;h2&gt;Additional Beans&lt;/h2&gt;

&lt;p&gt;This mechanism also supports having more than one container &lt;em&gt;type&lt;/em&gt;&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
jms {
    containers {
        other {
            meta {
                parentBean = "standardJmsListenerContainer"
            }
            connectionFactoryBean = "otherJmsConnectionFactory"
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;This creates a new container type called &lt;code&gt;other&lt;/code&gt; that inherits all of the configuration from the &lt;code&gt;standard&lt;/code&gt; container, but overrides the connection factory.&lt;/p&gt;

&lt;p&gt;You would then use this container by specifying the container on the listener.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import grails.plugin.jms.Subscriber

class ListeningService {
    
    @Subscriber(container = "other")
    void interestingStuff(payload) {
        
    }
    
}
&lt;/pre&gt;

&lt;h2&gt;The Point&lt;/h2&gt;

&lt;p&gt;The point of this article is not specifically to talk about the JMS plugin. This approach to bean configuration seems to work quite well when users need access to the underlying beans in an optional manner. This may be an approach that other plugin authors might want to adopt.&lt;/p&gt;</description><link>http://ldaley.com/post/435520332</link><guid>http://ldaley.com/post/435520332</guid><pubDate>Tue, 09 Mar 2010 10:42:53 +1100</pubDate><category>software</category><category>grails</category></item><item><title>Using Grails's JSON support with HTTPBuilder</title><description>&lt;p&gt;I am currently working on a set of JSON over HTTP web services APIs between Grails applications. &lt;a href="http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.1.7%20XML%20and%20JSON%20Responses" title="6. The Web Layer"&gt;Producing JSON content in Grails applications&lt;/a&gt; is ridiculously trivial, but the story on consuming content is not so clear.&lt;/p&gt;

&lt;p&gt;I am using &lt;a href="http://blog.thomnichols.org/" title="Thom Nichols"&gt;Tom Nichol&lt;/a&gt;&amp;#8217;s &lt;a href="http://groovy.codehaus.org/modules/http-builder/" title="HTTP Builder - News"&gt;HTTPBuilder&lt;/a&gt; for consumption. It&amp;#8217;s a great library, but does take a little getting used to. Fortunately, the documentation is excellent.&lt;/p&gt;

&lt;p&gt;HTTPBuilder ships with JSON support based on &lt;a href="http://www.jroller.com/aalmiray/" title="Andres Almiray's Weblog : Weblog"&gt;Andres Almiray&lt;/a&gt;&amp;#8217;s &lt;a href="http://json-lib.sourceforge.net/" title="Maven - Json-lib::Welcome"&gt;json-lib&lt;/a&gt;. That works fine, but I was worried about a potential impedance mismatch between json-lib&amp;#8217;s encoding/decoding and Grails&amp;#8217;.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s how I configured HTTPBuilder to use Grails&amp;#8217; JSON bits for encoding/decoding JSON data…&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ParserRegistry
import groovyx.net.http.ContentType.JSON

import org.apache.http.entity.EntityTemplate
import org.apache.http.entity.ContentProducer
import org.apache.http.message.BasicHeader

// create a builder instance
def builder = new HTTPBuilder()

// the closure that takes a HttpServletResponse and returns an object
def jsonParser = { response -&amp;gt;
    grails.converters.JSON.parse(new InputStreamReader(response.entity.content, ParserRegistry.getCharset(response)))
}

// the closure that takes an object and returns an org.apache.http.HttpEntity
def jsonEncoder = { value -&amp;gt;
    def json = value instanceof Closure ? new grails.web.JSONBuilder().build(value) : new grails.converters.JSON(value)
    def producer = [writeTo: { OutputStream out -&amp;gt; out.withWriter { json.render(it) } }] as ContentProducer
    def entity = new EntityTemplate(producer)
    entity.contentType = new BasicHeader("Content-Type", JSON.toString())
    entity
}

// for each JSON content type, install the handler
JSON.contentTypeStrings.each {
    builder.parser."$it" = jsonParser
    builder.encoder."$it" = jsonEncoder
}
&lt;/pre&gt;

&lt;p&gt;Note that you have to configure each created HTTPBuilder instance.&lt;/p&gt;

&lt;p&gt;Here is some contrived example usage. We are calling a JSON “mirror” service that simply just returns the JSON it was sent.&lt;/p&gt;

&lt;pre class="brush: groovy"&gt;

import grails.plugin.spock.*

import groovyx.net.http.Method.POST
import groovyx.net.http.ContentType.JSON

class HttpBuilderWithGrailsJsonSpec extends UnitSpec {

    void "test it all works like it should"() {
        given: "a configured HTTP builder"
        def builder = new HTTPBuilder("http://jsonmirror.org")
        // configure the builder as per above
        
        when: "I post '{a: 1}' to the JSON mirror service"
        def requestMethod = POST
        def responseContentType = JSON
        def result = builder.request(requestMethod, responseContentType) {
            def requestContentType = JSON
            send(requestContentType) {
                a = 1
            }
        }
        
        then: "I get the JSON '{a: 1}' returned"
        result.a == 1
    }
}
&lt;/pre&gt;</description><link>http://ldaley.com/post/410169928</link><guid>http://ldaley.com/post/410169928</guid><pubDate>Thu, 25 Feb 2010 13:01:00 +1100</pubDate><category>software</category><category>grails</category></item></channel></rss>

