Spock Web Console

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

ObjectSpec2

Published 1 week ago by Eric
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
class Animal {
}

class Bear extends Animal {
}

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

First we'll create a Bear object. The bear needs:
* a Name - what type should we use to store the name?)
* Offspring - what is a bear's offspring? How can we represent it?
* a function to tell if it's hibernating or not
* Says "GROWL!" when you call speak()
""")
class ObjectSpec extends Specification {
    def "Testing the bear"() {
        when: "Create a Bear Class so the test passes:"

        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"

        and: "We add all of the cubs to the offspring 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"() { }
}