Home > Groovy, TDD > Story time with easyb

Story time with easyb

Everyone loves a good story.
 

Star Wars Trilogy

 

With easyb, you can write stories in your code!

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {}
    and "Alderaan", {}
    and "Alderaan is targeted by the Death Star", {}
    when "the Death Star fires", {}
    then "Alderaan is destroyed", {}
 }

You probably could’ve written that with the stakeholders yelling over shoulder. No – the Death Star should destroy Yavin IV, not Alderaan!!! If you’re writing readable code in front of them, you might be able to get them to make a decision while you’re at your keyboard.

Now you have executable documentation, and the stakeholders can leave the party. And once they’re gone, you can move on to writing some Groovy code to fill in those empty squiggly braces:

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {
        deathStar = new DeathStar()
    }
    and "Alderaan", {
        alderaan = new Planet(name:"Alderaan")
        Galaxy.planets << alderaan
    }
    and "Alderaan is targeted by the Death Star", {
        deathStar.target = alderaan
    }
    when "the Death Star fires", {
        deathStar.fire()
    }
    then "Alderaan is destroyed", {
        Galaxy.planets.shouldNotHave alderaan
    }
}

Now run it and watch it fail. Ah, the joy of xDD…

From here, you can write the DeathStar, Planet, and Galaxy classes you need to make it pass. Run it again! Refactor! Repeat!

Now you have documentation that’s readable, executable, and verifies that your code does what it’s supposed to do! Wasn’t that easy?

Advertisements
Tags: , , ,
  1. July 29, 2009 at 1:21 pm

    Of course, Spock doesn’t fear the Death Star either:

    class DeathStar extends Specification {
    def “the Death Star destroys Alderaan”() {
    given: “the Death Star”
    def deathStar = new DeathStar()

    and: “Alderaan”
    def alderaan = new Planet(name: “Alderaan”)
    Galaxy.planets << alderaan

    and: "Alderaan is targeted by the Death Star"
    deathStar.target = alderaan

    when: "the Death Star fires"
    deathStar.fire()

    then: "Alderaan is destroyed"
    !Galaxy.planets.contains(alderaan)
    }
    }

  2. July 29, 2009 at 4:03 pm

    @Peter – thanks for sharing!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: