user1047912
user1047912

Reputation:

The After hook in cucumber

Folks,

I am having some trouble working with the Afterhook. I have organized my tests in folders like this:

features/Accounts/accounts_api.feature
features/Accounts/step_definition/account_steps.rb

features/labs/create_lab.feature
features/labs/step_definition/labs_steps.rb

Now I have an After hook present in the step definition of the Accounts feature, I want that hook to run after every scenario of the "Accounts" feature, but I do not want it to run after every scenario of the "labs" feature. I tried this:

cucumber --tags @newlabs

the above should run all the scenarios present in the labs feature tagged as newlabs but what I am seeing is that once the scenario tagged as@newlabs runs the @after hook present in the step definition of Accounts starts to run. I am thinking why is this happening, am I using the hook in the wrong way or is my overall understanding of hooks wrong?

Thanks a lot for taking the time to respond, this helps a lot.

Upvotes: 2

Views: 3953

Answers (2)

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

Possibly you define After hook in wrong place. Note that After hook (as well as other hooks) must be defined in the .rb, not in the .feature file. Common place for hooks is features/support/hooks.rb. You will define your hook this way:

# features/support/hooks.rb
After('@newlabs') do # will run after each scenario tagged with @newlabs 
   # your teardown ruby code 
end

# features/Accounts/accounts_api.feature
@newlabs # tag all scenarious of this feature with @newlabs tag
Feature: your feature

Scenario: your scenario
  Given: ...
  When: ...
  Then: ...

In cucumber output you won't see that After hook is executed (unless you output something to STDOUT from the hook definition) - hooks will run implicitly.

Upvotes: 2

BaronVonBraun
BaronVonBraun

Reputation: 4293

Hooks don't care what step definition script they're located in and will run for every scenario. Or, more specifically, your after hook will run after every scenario that runs, for every feature, regardless of the tags you pass in to Cucumber.

If you want a little more control over that, check out the Cucumber wiki page on hooks and look in the section called 'Tagged hooks'.

Upvotes: 2

Related Questions