Skip to content

Setup Code

Jens Finkhaeuser edited this page Feb 17, 2015 · 2 revisions

Setup Code

Cucumber projects quite often require

  1. Some set up code to be run before or after each scenario, or
  2. some set up code to be run once at the start of a test suite.

In either case, cucumber provides hooks to deal with that, most notably the Before hook.

Setup Per Scenario

The most simple case it to put your setup code right into the Before hook:

# env.rb
Before do
  # do something here
end

Complex Setup

As a test suite grows, that simple hook might also grow to contain lots of code. The natural evolution is to put much of the setup code into a function, and call the function from the hook.

# env.rb
def do_something_complex
end

Before do
  do_something_complex
end

In the interest of avoiding namespace pollution in Ruby, the standard Ruby recommendation is to put your functions into modules. To deal with this, cucumber introduces a World object (see LapisLazuli usage), so the complete example would be this:

# env.rb
module MyModule
  def do_something_complex
  end
end

World(MyModule)

Before do
  do_something_complex
end

Single-Execution Hooks

Some hooks should be run only once, when the test suite starts. That's easy to implement in the module now:

# env.rb
module MyModule
  @@run_once = nil

  def do_something_complex_once
    if not @@run_once.nil?
      return
    end
    @@run_once = true

    # do stuff
  end
end

World(MyModule)

Before do
  do_something_complex_once
end

LapisLazuli functionality

As of versions > 0.6.0, LapisLazuli provides helper functionality for running setup code once, at the start of a test suite. See the WorldModule::Hooks for details.