Search code examples
sortinggrailstestingmappinggrails-orm

grails: testing 'sort' mapping in a domain class


Given the example from grails doc:

class Airport {
    …
    static hasMany = [flights: Flight]
    static mapping = {
        flights sort: 'number', order: 'desc'
    }
}

How can one test sorting?


Solution

  • As stated in the docs, it does not work like written. You have to add static belongsTo = [airport:Airport] to Flight.

    Without belongsTo you get the following error:

    Default sort for associations [Airport->flights] are not supported with unidirectional one to many relationships.

    With belongsTo the test could look like this:

    class SortSpec extends IntegrationSpec {
        def "test grails does sort flights" () {
            given:
            def airport = new Airport()
            airport.addToFlights (new Flight (number: "A"))
            airport.addToFlights (new Flight (number: "C"))
            airport.addToFlights (new Flight (number: "B"))
            airport.save (failOnError: true, flush:true)
    
            when:
            def sortedAirport = airport.refresh() // reload from db to apply sorting
    
            then:
            sortedAirport.flights.collect { it.number } == ['C', 'B', 'A']
        }
    }
    

    But.. it doesn't make much sense to write a test like this because it checks that grails applies the sorting configuration. Why would I want to test grails? Test your code and not the framework.