GrailsInAction / graina2

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

"Listing 5.6 Where queries in action" requires several changes to get it to work #19

Closed philfriesen closed 10 years ago

philfriesen commented 11 years ago

This post is going to ramble a bit.

The QueryIntegrationSpec test class in this listing failed on the "Query against a range value" method. Looking at the sample data in Bootstrap.groovy, I concluded that the assertion needed to change

from: users*.loginId == ["phil", "peter", "glen", "frankie", "chuck_norris", "admin"]
  to: users*.loginId == ["phil", "jeff", "graeme", "frankie", "burt", "admin"]

I wasn't getting the admin user, so after adding some println's I found that the save for admin was failing silently. To get it to work, I changed the code

from:
def profile = new Profile(email: "admin@yourhost.com")
new User(loginId: "admin", password: "secret", profile: profile).save()

to:
def profile = new Profile(fullName: "Administrator", email: "admin@yourhost.com")
def user = new User(loginId: "admin", password: "secret", profile: profile, dateCreated: new Date())
user.save(failOnError: true, flush: true)
println "Created user " + user + " dateCreated=" + user.dateCreated

I also added a println to the createSampleData() method and discovered that the createAdminUserIfRequired() method is called before the createSampleData() method in the Bootstrap.groovy code:

    def init = { servletContext ->
        environments {
            development {
                if (!Post.count()) createSampleData()
            }
            test {
                if (!Post.count()) createSampleData()
            }
        }

        // Admin user is required for all environments
        createAdminUserIfRequired()
    }

So it appears that the environments {} block is a configuration instruction that will get executed after any method calls that come after that block. It would be helpful if you added a comment that tips us off to the execution order of what happens inside the init block.

Thanks!

pledbrook commented 11 years ago

That's interesting. Yes, it's probably worth mentioning that (in a sidebar I think), particularly as it's unexpected.

BTW, the admin user creation is fixed in the sample source code. There is still a problem around the login IDs in the test, but there is a separate issue for that.

pledbrook commented 10 years ago

Added a sidebar to explain the execution ordering. I pointed out that there is no guarantee of the order, since it's not documented as far as I'm aware. So it could easily change in a future version.