Search code examples
javacucumberscenarios

Cucumber pass whole example to a step


I want to pass a whole example to some test step as an Map object. How can it be achieved?

lets say I have scenario

Scenario Outline: some description text
When user do something
Then the user should see something
Examples: set 1
  | Param Title |
  | value 1     |
Examples: set 2
  | Param Title | Param Title 2 |
  | value 2     | value 3       |

in the step definition of When user do something I want a map that would have map {"Param Title":"value 1"} for first example and {"Param Title":"value 2","Param Title 2":"value 3"} for the second example. Is there any way to do that in cucumber or my only option is to write same scenario multiple times for each example?


Solution

  • 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.