什么是Grails相当于Rspec的让?

时间:2017-01-21 00:06:11

标签: unit-testing grails rspec

来自Rails,我在Grails的单元测试中遇到了困难。 Grails中以下内容的等效内容是什么?

let(:some_variable) { SomeObject.new(name: 'Blabla', ...) }

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

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

    then:
    response.json.size() == 2
}

因此测试将有两个变量,响应将产生这两个对象的数组,大小为2.

1 个答案:

答案 0 :(得分:1)

简单案例:

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