Unit testing 什么是Rspec的let的Grails等价物?

Unit testing 什么是Rspec的let的Grails等价物?,unit-testing,grails,rspec,Unit Testing,Grails,Rspec,来自Rails,我在Grails中进行单元测试时遇到了困难。在Grails中,以下内容的等价物是什么 let:some_变量{SomeObject.newname:'Blabla',…} 我想定义一些可能在每个测试中使用的变量。此外,我希望保存对象,如: def "some test"() { // given variable1 and variable2 then: response.json.size() == 2 } 因此,测试将有两个变量,响应将生成这两个对

来自Rails,我在Grails中进行单元测试时遇到了困难。在Grails中,以下内容的等价物是什么

let:some_变量{SomeObject.newname:'Blabla',…}

我想定义一些可能在每个测试中使用的变量。此外,我希望保存对象,如:

def "some test"() {
    // given variable1 and variable2

    then:
    response.json.size() == 2
}
因此,测试将有两个变量,响应将生成这两个对象的数组,大小为2。

简单情况:

@TestFor(SomeController)
class SomeControllerSpec extends Specification {
    def "some test"() {
        given:
            def var1 = new SomeObject(name:"AAA").save(flush:true)
            def var2 = new SomeObject(name:"BBB").save(flush:true)
        when:
            controller.someAction() 
            // assuming someAction fetches the SomeObject instances 
            // and marshals a JSON Response
        then:
            controller.response.json.size() == 2
    }
}
或许:

@TestFor(SomeController)
class SomeControllerSpec extends Specification {

    // var1 and var2 are saved to the DB, and persist across all
    // the tests in this specification
    def var1 = new SomeObject(name:"AAA").save(flush:true)
    def var2 = new SomeObject(name:"BBB").save(flush:true)

    def "some test"() {
        when:
            controller.someAction() 
        then:
            controller.response.json.size() == 2
    }
}

您提到了变量和响应,但问题中缺少了您正在寻找的操作。你能详细说明这个问题吗?但是让我们允许你在测试中重用这个实现。这似乎需要在每个示例中重复,或者将该操作放在规范的设置阶段。也有可用的设置和清理方法。检查Grails文档中关于测试的部分。您应该编辑您的答案。让我们进行记忆,只创建一次对象,然后返回它,而不是每次都返回新实例。