Disabling validation restriction in grails command unit for unit testing (with Spock)

I am trying to write some unit tests to test Command objects. When my command object has many fields with many validation rules, setting the command object for each test case becomes too verbose and repetitive.

Let's say I have this command object:

class MemberCommand {
    String title
    String name
    String phone
    static constraints = {
        title(blank: false, inList: ["Mr", "Mrs", "Miss", "Ms"])
        name(blank: false, maxSize:25)
        phone(blank: false, matches: /\d{8}/)
    }
}

I want to verify this by doing something like this:

class ValidationTitle extends UnitSpec {
    def "title must be one of Mr, Mrs, Miss, Ms"() {
        setup:
        def memberCommand = new MemberCommand()
        // I don't want to do:
        // memberCommand.name = "Spock" 
        // memberCommand.phone = "99998888"
        // Instead, I want to disable other constraints, except the one for title
        mockForConstraintsTests MemberCommand, [memberCommand]

        when:
        memberCommand.title = t

        then:
        memberCommand.validate() == result

        where:
        t << ["Mr", "Mrs", "Miss", "Ms", "Dr", ""]
        result << [true, true, true, true, false, false]
    }
}

, , memberCommand.validate(), , "Mr" . , , , . , , .

( Spock) grails?

, ?

.

+3
1

. , title .

( ) :

def validAttributes = [ title: 'Mr', name: 'Spock', phone: '99998888' ]

def "title must be one of Mr, Mrs, Miss, Ms"() {
    setup:
    def memberCommand = new MemberCommand(validAttributes)
    mockForConstraintsTests MemberCommand, [memberCommand]

    when:
    memberCommand.title = t

    then:
    memberCommand.validate() == result

    where:
    t << ["Mr", "Mrs", "Miss", "Ms", "Dr", ""]
    result << [true, true, true, true, false, false]
}

- "" , ( ). .

:

def "title must be one of Mr, Mrs, Miss, Ms"() {
    setup:
    def memberCommand = new MemberCommand()
    mockForConstraintsTests MemberCommand, [memberCommand]

    when:
    memberCommand.title = t
    memberCommand.validate()

    then:
    memberCommand.errors['title'] == result

    where:
    t << ["Mr", "Mrs", "Miss", "Ms", "Dr", ""]
    result << [null, null, null, null, 'not.inList', 'not.inList']
}
+3

All Articles