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

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.

Related posts:

  1. Configuration is Code: Presented on Grails Spring Bean Builder (a.k.a. Groovy Spring Builder)
  2. Okay, Grails, That Was Cute: Taglibs
  3. The Joy of Behavior Driven Development (BDD), or, Re-writing Code in Asserts is Not Unit Testing
  4. “Grails Persistence with GORM and GSQL” has gone public
This entry was posted in To Be Categorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • Taras Matyashovsky

    Thanks, was very useful for me.

  • http://amitjaindelhi.blogspot.com Amit

    Thanks a ton!!

  • Ryan M

    This is great for testing frameworks like spock because I have to clean up between each iteration of the test and grails will only handle this between tests, not iterations. Thanks!

  • Categories