Skip to content
This repository was archived by the owner on Nov 16, 2018. It is now read-only.
aslakhellesoy edited this page Aug 13, 2010 · 36 revisions

Cucumber provides a number of hooks which allow us to run blocks at various points in the Cucumber test cycle. You can put them in your support/env.rb file or any other file under the support directory, for example in a file called support/hooks.rb. There is no association between where the hook is defined and which scenario/step it is run for, but you can use tagged hooks (see below) if you want more fine grained control.

All defined hooks are run whenever the relevant event occurs. For example all Before hooks defined throughout the required code will be run before the first step of each scenario.

Scenario hooks

Before do
  # Do something before each scenario.
end
After do |scenario|
  # Do something after each scenario.
  # The +scenario+ argument is optional, but
  # if you use it, you can inspect status with
  # the #failed?, #passed? and #exception methods.

  if(scenario.failed?)
    subject = "[Project X] #{scenario.exception.message}"
    send_failure_email(subject)
  end
end

Step hooks

AfterStep do
  #do something after each step
end

Global hooks

If you want something to happen once before any scenario is run – just put that code at the top-level in your env.rb file (or any other file in your features/support directory. Use Kernel#at_exit for global teardown. Example:

my_heavy_object = HeavyObject.new
my_heavy_object.do_it

at_exit do
  my_heavy_object.undo_it
end

Tagged hooks

Only available in Cucumber 0.3.0 and above

Sometimes you may want a certain before or after hook to run only for certain scenarios. This can be achieved by associating a hook with one or more tags. Example:

Before('@cucumis', '@sativus') do
  # This will only run before scenarios tagged
  # with @cucumis or @sativus.
end

Think twice before you use this feature, as whatever happens in hooks is invisible to people who only read the features. You should consider using background as a more explicit alternative if the setup should be readable by non-technical people.

Clone this wiki locally