Cucumber pass whole example to a step

The cost of writing a step definition is trivial compared to the complexity you are adding by trying to pass your map into a generic step def.

If you implement all your step definitions as single calls to a helper method it really doesn’t matter if you have lots of step definitions that do the same thing. When you follow this pattern your step definitions perform one function, they translate a string phrase into a method call.

Let me give you some examples

Given I am logged in
Given I am logged in as an admin
Given Fred is logged in
Given Bill is logged in
Given Sam is logged in as an admin

Now you would probably want to write just one step definition for all of these, but that is actually a mistake and a false optimisation. Its much simpler to do the following (all examples are in ruby)

Given 'I am logged in' do
  @i ||= create_user
  login as: @i
end

Given 'I am logged in as an admin' do
  @i ||= create_admin
  admin_login as: @i
end

Given 'Fred is logged in' do
  @fred ||= create_user(first_name: 'Fred')
  login as: @fred
end

Given 'Bill is logged in' do
  @bill ||= create_user(first_name: 'Bill')
  login as: @fred
end
  
Given 'Sam is logged in as an admin' do
  @sam ||= create_admin(first_name: 'Sam')
  login as: @sam
end

All the work here is being done by the helper methods (create_user, create_admin, login, admin_login), so it doesn’t matter if you have twenty step definitions that do login so long as they all use the helper methods to do the work you have no real code duplication, and you have simplicity and consistency.

This is a completely different approach to the one you are currently taking. But a valid answer to any cuke question involving doing complex things with steps and step definitions is to stop trying to do complex things and instead more simple things.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top