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])
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.
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])