Spock 测试 returns 一个空模型

Spock test returns a null model

这个问题很奇怪,因为几乎相同的操作 returns 正确的模型,不同之处在于我不是渲染模板而是视图。

首先是控制器动作:

如您所见,此处存在渲染模型

def saveAjax(Author authorInstance){
    if(!authorInstance.validate()){
        respond view: 'index', authorInstance.errors
    } else {
        def author = new Author(username: authorInstance.username)
        authorService.save(author)
        render(template: 'author_row', model:[author:author]) //<--here the model is correct           
    }
}

如果我将“模板”与“视图”交换,则测试通过

服务:

Author save(Author author) {
    return author?.save(flush: true)
}

测试本身:

void "Test the saveAjax action"() {

    when:"you do not have the correct params"
        controller.saveAjax(new Author())

    then:"expect to be redirected to index"
        view == 'index'

    when:"you have the correct params"
        response.reset()
        controller.saveAjax(new Author(username: "Alice"))

    then:"expect to have model author"
        model.author //<-- here I get author = null
}

错误:

Condition not satisfied:

model.author
|     |
|     null
[authorInstance:daily.journal.Author : (unsaved)]

我知道您可以检查渲染模板的内容,但我明确针对模型。有机会测试吗?

原来我偶然发现了 Grails 配置约定 的东西。尽管该模型被命名为 author,但它只能作为 authorInstance 进行测试。所以我改成了:

then:"expect to have model author"
      model.authorInstance

在规范中并且...它 通过了 。如果有人能向我解释为什么,我仍然会很高兴?

因为您的作者没有通过验证。正如您在这里看到的:authorInstance:daily.journal.Author : (unsaved)。 由于验证错误未保存,您可以将您的服务更新为

return author?.save(flush: true, failOnError: true)

接收验证异常,或者您可以打印测试中的错误。