Using Hooks

Cucumber supports hooks, which are blocks of code that run before or after each scenario. You can define them anywhere in your support or step definition layers, using the methods Before and After.

To test them, take any Cucumber project and try adding a file features/support/hooks.rb that looks like this:

 Before ​do
  puts ​"Go!"
 end
 
 After ​do
  puts ​"Stop!"
 end

If you run cucumber, you’ll see the two messages printed in the output at the beginning and end of the scenario. Cucumber’s Before and After hooks are a lot like the setup and teardown methods in the xUnit family of testing tools.

The most common use of Before and After hooks is to clear up any residual state left in external systems like databases so ...

Get The Cucumber Book, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.