Spock Web Console

subscribe to the feed Subscribe
LoopSpec (via #spockwebconsole)
tweet this script Tweet

LoopSpec

Published 1 week ago by Eric
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.Narrative
import spock.lang.Specification

@Narrative("""
Loops are a way to repeat commands or iterate over lists of things.

There are many types of loops in the examples below. 

Try to make the tests pass by seeing how the loop behaves **AND** how it affects the variables in the tests
""")
class LoopSpec extends Specification {
    def "Traditional for"() {
        given:
        def loopCount = 0

        when:
        for(def loop = 0; loop < 10; loop++) {
            loopCount++
        }

        then:
        loopCount == null
    }

    def "for in list"() {
        given:
        def count = 0

        when:
        for(loop in 1..10) {
            count = count + loop
        }

        then:
        count == null
    }

    def "for each in list of strings"() {
        given:
        def count = 0
        def list = ["Eric", "Bob", "Frank"]

        when:
        for(name in list) {
            count++
        }

        then:
        count == null
    }

    def "while loop"() {
        given:
        def count = 0

        when:
        while (count < 5) {
            count++
        }

        then:
        count == null
    }

    def "each in range"() {
        given:
        def count = 0

        when:
        (1..10).each {
            count++
        }

        then:
        count == null
    }

    def "each list"() {
        given:
        def count = 0

        when:
        ["foo", "bar"].each {
            count++
        }

        then:
        count == null
    }


    def "BONUS - easier count on lists"() {
        given:
        def list = ["Eric", "Bob", "Frank"]

        expect:
        list.size() == null
    }

    def "BONUS - Nested loops"() {
        given:
        def loopCount = 0

        when: "As with if (and any) statements, we can nest them"
        for(def loop = 0; loop < 10; loop++) {
            for(def loopTwo = 0; loopTwo < 10; loopTwo++) {
                loopCount++
            }
        }

        then:"How many times did the loop happen?"
        loopCount == null
    }
}