rapaul.com

A technical blog written by Richard Paul

Cucumber World With Groovy

Cucumber provides the ability to create a world in which you can expose useful methods for the testing environment. This post briefly details how to expose these methods when using Groovy with Cuke4Duke.

1
2
3
4
5
6
7
8
9
10
11
12
Feature: World
In order to make useful methods available
As a tester
I want the world to be full of wonderful methods

Scenario: Greet
When I greet
...

Scenario: Farewell
When I farewell
...

These scenarios capture the ability to greet and farewell our customers. The matching step definitions are shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
// hello_steps.groovy
import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*

this.metaClass.mixin(cuke4duke.GroovyDsl)

When(~'I greet') {
  assertThat(hello(), is('hi'))
}

When(~'I farewell') {
  assertThat(goodbye(), is('ciao'))
}

You will notice that we haven’t defined the hello() or goodbye() methods anywhere in our step definition file. We are assuming these methods are provided by the world environment that Cucumber provides. This allows the world methods to be shared between many different step definition files.

Next we define the world environment. Instead of defining all methods in a single class, we can group the methods into individual classes and make them all available on the world class at runtime using Groovy’s mixin support.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// env.groovy
this.metaClass.mixin(cuke4duke.GroovyDsl)

class Greeter {
  def hello() {
    'hi'
  }
}

class Fareweller {
  def goodbye() {
    'ciao'
  }
}

class World {}

World() {
  World.mixin Greeter, Fareweller
  new World()
}

The World() call is part of Cucumber’s DSL, here we use it to publish an instance of our World class thus making both hello() and goodbye() available in the testing environment (note that the name of the World class is not important).

Comments