GrailsInAction / graina2

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

Error in code in 6.1.2, Listing 6.x (MEAP v7) #9

Open LukeMarlin opened 11 years ago

LukeMarlin commented 11 years ago
package com.grailsinaction
import grails.test.mixin.TestFor
import spock.lang.Specification
import grails.test.mixin.Mock
@TestFor(PostController)
@Mock(User)
class PostControllerSpec extends Specification {
    def "Get a users timeline given their id"() {
        given: "A user with posts in the db"
            User chuck = new User(userId: "chuck_norris", password:
                                "password").save(failOnError: true)
            chuck.addToPosts(new Post(content: "A first post"))
            chuck.addToPosts(new Post(content: "A second post"))

        and: "A userid parameter"
            params.id = chuck.userId

        when: "the timeline is invoked"
            def model = controller.timeline()

        then: "the user is in the returned model"
            model.user.userId == "chuck_norris"
            model.user.posts.size() == 2
    }
}

This code will produce an error when we launch grails test-app:. The error is: "No signature of method com.grailsinaction.User.addToPosts() is applicable for argument types : (com.grailsinaction.Post) values: [com.grailsinaction.Post : (unsaved)]"

To correct it, I had to modify the @Mock statement as follows : @Mock([User, Post])

pledbrook commented 11 years ago

Right. At some point (I can't remember exactly when) the behaviour in Grails changed such that you have to explicitly mock any associations you use in the test. We'll try to get that updating soon.