Jan 03 2009
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.
Popularity: 1% [?]
One Response to “Useful Grails Integration Testing Snippet: Delete All Instances of Domain Classes”
Leave a Reply
Additional comments powered by BackType

Thanks, was very useful for me.