Jan 03 2009

Useful Grails Integration Testing Snippet: Delete All Instances of Domain Classes

Published by Robert Fischer at 3:33 PM under To Be Categorized

Just thought I’d share this quick:

import org.codehaus.groovy.grails.commons.ApplicationHolder
 
class FooTests extends GroovyTestCase {
 
  def sessionFactory
 
  void setUp() {
    (ApplicationHolder.application.getArtefacts("Domain") as List).each {
      it.newInstance().list()*.delete()
    }
    sessionFactory.currentSession.flush()
    sessionFactory.currentSession.clear()
  }
}

That code deletes all the instances of all the domain classes. Yes, the transactional aspect of Grails integration tests should make sure everything is rolled back properly. But there’s always something that sneaks into the database one way or another (often as the result of exception handling or other weirdness), so I like to be thorough. I had the same problem back when I was developing Rails. If you have that problem, feel free to have at the above code.

Also note the usefulness of Spring dependency injection here, despite using a dynamic language. It has been asserted that “real” dynamic languages don’t need Spring, but I find that assertion really, really odd.

Popularity: 1% [?]

One response so far

One Response to “Useful Grails Integration Testing Snippet: Delete All Instances of Domain Classes”

  1. Taras Matyashovskyon 05 Feb 2009 at 4:56 PM

    Thanks, was very useful for me.

Trackback URI | Comments RSS

Leave a Reply

Additional comments powered by BackType

Green Web Hosting! This site hosted by DreamHost.