Spock Web Console

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

ObjectSpec

Published 1 week ago by Eric
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
class Animal {
    def name
    def offspring = []
    def speak() { "" }
}

enum Season {
    SPRING, SUMMER, FALL, WINTER
}

class Bear extends Animal {
    Season season

    def speak() { "Growl!" }

    def isHibernating() {
        if(season == Season.WINTER)
            true
        else
            false
    }
}

@Narrative("""
Creating your own Objects and methods!

First we'll create a Bear 

Here we'll 
""")
class ObjectSpec extends Specification {
    def "Testing the bear"() {
        when: "Create a Bear Class so the test passes:"
        def bear = new Bear(name:"Scratchy")

        then: "Only use the `when` block to make this pass"
        bear.name == "Scratchy"
        bear.speak() == "Growl!"
        bear.isHibernating() == false

        when: "Change the season to winter"
        bear.season //??

        then: "the bear is hibernating"
        bear.isHibernating() == true
    }

    /*
    All animals have some things in common. Lets make an `Animal` class. Our Bear can `extend` the animal.

    Take the common aspects of animals (name, offspring) and move it to the Animal class - BUT keep the Bear test passing!
     */
    def "Offspring"() {
        given: "Create a motherBear and cubs that will be the offspring"
        def motherBear = new Bear(name:"Scratchy")
        def cub1 = null
        def cub2 = null

        and: "We add all of the cubs to the offspring list"
        motherBear.offspring // HINT: Offspring is a list!

        expect: "Mother bear has 2 cubs"
        motherBear.offspring.size() == 2

        and: "Her first born doesn't have any cubs"
        motherBear.offspring.first().offspring.size() == 0
    }
}

/*
What other aspects are common in animals? Mammals? Reptiles?
What about Flying? Both Mammals and Reptiles can fly. For those we can use a Trait:
 */

trait FlyingAbility {
    String fly() { "I'm flying!" }
}

class Canary extends Animal implements FlyingAbility {
    def name = "Tweety"
    def speak() { "Tweet, tweet!" }
}

// Creat a test case to make this pass

class TraitSpec extends Specification {
    def "Ensure a bear can not fly"() { }
    def "A Canary can fly"() { }
}