【问题标题】:Spock test returns a null modelSpock 测试返回一个空模型
【发布时间】:2018-08-02 09:26:46
【问题描述】:

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

首先是 controller 动作:

如您所见,渲染的模型在这里存在

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           
    }
}

如果我将 'template' 与 'view' 交换,则测试通过

服务:

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 spock


    【解决方案1】:

    结果我发现了一个 Grails convention over configuration 的东西。尽管模型被命名为作者,但它只能作为作者Instance进行测试。所以我把它改成:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 您如何解释:当我将“Instance”放在 model.author 的末尾时,它通过了?
      • respond view: 'index', authorInstance.errors 我认为它生成到:render view: 'index', model: [authorInstance: authorInstance]
      • 好吧,它验证了它并且作者被保存了..然后在测试中它说它没有被保存。这没有意义吧?
      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多