GrailsInAction / graina2

Source code for the 2nd edition of Grails in Action
90 stars 91 forks source link

MEAP v9, chapter 3, section 3.4.2 : sorting gotchas #28

Open marcpa00 opened 11 years ago

marcpa00 commented 11 years ago

I think that sorting should be introduced in more details at end of section 3.4.2 or it should not be touched until later in the book.

Rationale

If one feels the urge to add spock tests verifying sort behavior of Post and user.posts, as I did after reading section 3.4.2, they're in for a bumpy ride. Here is what observed:

Because of that, tirival code to check for sorting behavior does not work and writing tests that work is not easy for the intended audience (from my point of view).

If you think it is worth it to address the subject of sorting at that point, I would suggest adding the following tests to PostIntegrationSpec with a pargraph or two discussing the details :


    def "Ensure posts linked to a user are sorted by date descending, earliest first"() {

        given: "A user with several posts"
        User user = new User(loginId:'joe', password: 'secret')
        user.addToPosts(new Post(content:'First post')).save(failOnError: true, flush: true)
        user.addToPosts(new Post(content:'Second post')).save(failOnError: true, flush: true)
        user.addToPosts(new Post(content:'Third post')).save(failOnError: true, flush: true)

        when: "The user is saved"
        user.save(failOnError: true)

        then: "The posts appear sorted by date created, descending"
        User.withNewSession { session ->
            User.get(user.id).posts.collect { it.content } == [ 'Third post', 'Second post', 'First post' ]
        }
    }

    def "Ensure listing post collection is using sort order"() {
        given: "A user with several posts"
        User user = new User(loginId: "joe", password: 'secret')
        user.addToPosts(new Post(content: "B")).save(failOnError: true, flush: true)
        user.addToPosts(new Post(content: "C")).save(failOnError: true, flush: true)
        user.addToPosts(new Post(content: "A")).save(failOnError: true, flush: true)
        user.save(failOnError: true, flush: true)

        when: "the list of all posts is retrieved"
        List<Post> posts = Post.list()

        then: "The posts for user created are in date created order"
        posts.collect { it.content } == Post.list().sort { it.dateCreated }.reverse().collect { it.content }
    }

This is with

   static mapping = {
       posts sort: 'dateCreated', order: 'desc'
    }

specified in class User, and

    static mapping = {
        sort dateCreated: 'desc'
    }

specified in class Post.

pledbrook commented 11 years ago

This is a good point. I need to discuss this with Glen. Chapter 3 is soon to go into pre-production, so we should work out what approach to take pretty soon.

Thanks so much for the comprehensive report!