Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Grails dateCreated and lastUpdated for test data only?

I have several Grails 2.1 domain classes that include dateCreated and lastUpdated fields that GORM manages automatically, eg:

class Person {
    Date dateCreated
    Date lastUpdated
    String name
}

I want Grails to automatically fill in these fields at runtime, but I also want to create some test data where I can manually define the values of these dates. The trouble is that Grails automatically sets the values if these fields with an interceptor even when I have specifically set them.

I have seen this SO question which describes how to allow changes to dateCreated, but I need to change lastUpdated as well. Is this possible?

like image 829
Dan Vinton Avatar asked Nov 22 '12 15:11

Dan Vinton


2 Answers

Whoops, my mistake, the approach in the other question does work, but the entity in question was separately being saved somewhere else. It also seems that you need an explicit flush to make things work:

def withAutoTimestampSuppression(entity, closure) {
    toggleAutoTimestamp(entity, false)
    def result = closure()
    toggleAutoTimestamp(entity, true)
    result
}

def toggleAutoTimestamp(target, enabled) {
    def applicationContext = (ServletContextHolder.getServletContext()                                                           
                              .getAttribute(ApplicationAttributes.APPLICATION_CONTEXT))

    def closureInterceptor = applicationContext.getBean("eventTriggeringInterceptor")
    def datastore = closureInterceptor.datastores.values().iterator().next()
    def interceptor = datastore.getEventTriggeringInterceptor()

    def listener = interceptor.findEventListener(target)
    listener.shouldTimestamp = enabled
    null
}

def createTestPerson() {

    def luke = new Person(name: "Luke Skywalker")
    withAutoTimestampSuppression(luke) {

        def lastWeek = new Date().minus(7)
        luke.dateCreated = lastWeek
        luke.lastUpdated = lastWeek
        luke.save(failOnError: true, flush: true)
    }
}
like image 161
Dan Vinton Avatar answered Sep 23 '22 09:09

Dan Vinton


If it is an integration test you can use an hql update statement to manually set lastUpdated.

like image 30
TimJ Avatar answered Sep 22 '22 09:09

TimJ