ccy
ccy

Reputation: 1415

Can cucumber after hook get scenario variables?

My cucumber scenario is as follows:

Scenario: test add user
Given I logged in with email
When I add user with name test1 in my test
Then I should see my user
#After remove user with name test1

Some sample step definitions is as:

When /^add user with name (\w+) in my test$/ do |name|
    @test.add_user(name)
end

I would like to remove the user I just added after the test scenario has finished to keep the system clean. Can I achieve this by using After hook? I cannot find a way to pass the users name into the After hook.

Upvotes: 0

Views: 3584

Answers (1)

Jon M
Jon M

Reputation: 11705

There isn't really a way of specifically passing information into hooks, which is a good thing, your scenarios should be ignorant of whatever hooks may or may not be executed.

Hooks can get access to global state though, so you could easily add each created user to a global array, and use a hook to clean those users out:

# In step def
@test_users ||= []
@test_users << name
@test.add_user(name)

# In hook
@test_users.each { |u| @test.remove_user(u) }

It's worth pointing out that the database_cleaner gem is specifically designed for clearing out test data between tests or test suites, and may be able to provide you with what you want without having to hand-roll your own cleanup code.

Upvotes: 2

Related Questions