Fork me on GitHub

LD.

Music, software, life… and stuff.

[ Twitter ] [ GitHub ] [ Linked In ]

Brute force fixture cleanup in Grails

I am currently working on establishing a suite of functional tests. I am using the functional test features of the spock plugin to do this, which I’ll be writing more on in the near future.

Naturally, I am using the fixtures plugin to load my test data in the functional tests. However, the plugin provides no support for tearing down data. You generally don’t need to worry about this in integration tests because integration tests are by default wrapped in rollback-only transactions. This is not possible due to the nature of functional tests though.

In order to get something up and running quickly, I implemented this…

import groovy.sql.Sql
import grails.plugin.spock.FunctionalSpec

abstract class FunctionalSpecSupport extends FunctionalSpec {

    def dataSource
    def sessionFactory
        
    def cleanup() {
        sessionFactory.currentSession.flush()
        def db = new Sql(dataSource)
        db.withBatch { stmt ->
            stmt.addBatch("SET FOREIGN_KEY_CHECKS = 0")
            db.eachRow("SELECT table_name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '«SCHEMA»' AND table_type = 'BASE TABLE'") {
                stmt.addBatch("TRUNCATE table " + it.table_name)
            }
            stmt.addBatch("SET FOREIGN_KEY_CHECKS = 1")
        }
        sessionFactory.currentSession.clear()
    }
}   

All of my actual functional tests extend this FunctionalSpecSupport class. The cleanup() method is to Spock what tearDown() is to standard JUnit tests. That is, it’s invoked after every test. Also, due to historical reasons the project I am working on uses MySQL so the SQL above is specific to that DB, but the concept is portable.

That lacks finesse, but it get’s the job done.

Posted: Feb 19th, 2010 @ 5:09 pm

Tags: #software  #grails  

Comments

Archive · RSS · Theme by Autumn