Monday, December 28, 2015

Cucumber Step Definitions(Glue Code)

Glue Code is the code that interacts directly with your application. There are two kinds of Glue code – Step Definitions and Hooks.

Cucumber doesn't know how to execute your scenarios out-of-the-box. It needs Step Definitions to translate plain text Gherkin steps into actions that will interact with the system.

When Cucumber executes a Step in a Scenario it will look for a matching Step Definition to execute.

A Step Definition is a small piece of code with a pattern attached to it. The pattern is used to link the step definition to all the matching Steps, and the code is what Cucumber will execute when it sees a Gherkin Step.

To understand how Step Definitions work, consider the following Scenario:

Scenario: Some Apples
  Given I have 50 apples in my bag
The I have 50 apples in my bag part of the step (the text following the Given keyword) will match the Step Definition below:

@Given("I have (\\d+) apples in my bag")
public void  I_have_apples_in_my_bag(int apples){
System.out.format("Apples:%n\n",apples);
}

When Cucumber matches a Step against a pattern in a Step Definition, it passes the value of all the capture groups to the Step Definition's arguments.

Capture groups are strings (even when they match digits like \d+). For statically typed languages, Cucumber will automatically transform those strings into the appropriate type. For dynamically typed languages, no transformation happens by default, as there is no type information.

Cucumber does not differentiate between the five step keywords Given, When, Then, And and But.

Tip: Run cucumber feature file, it will generate the sample step definitions syntax for undefined steps.

Tip for effective and reusable code:
      1. Use Compound Steps to Build Up Your Language

      Compound steps (calling steps from steps) can help make your features more concise while still keeping your steps general—just don't get too carried away. For example:
      Given /^the user (.*) exists$/ do |name|
        # ...
      end
      
      Given /^I log in as (.*)$/ do |name|
        # ...
      end
      
      Given /^(.*) is logged in$/ do |name|
        Given "the user #{name} exists"
        Given "I log in as #{name}"
      end

      2. Use Parallel Step Definitions to Support Different Implementations for Features

      For example, running features against Selenium. Put these step definitions somewhere where they won't be auto-loaded, and require them from the command line or rake task.

No comments:

Post a Comment