Scenario background in cucumber

Sometimes, we need to execute certain steps, before every scenario in the same feature file. Backgrounds allow you to reuse same steps across multiple scenarios. For example – to test some feature, we might need to filter records before every scenario. So we can put the steps required to filter the records inside Background. These steps would be executed every time each scenario in the same feature file is executed. In below feature file, we have one step in the background (Given I filter some records). This step will be executed before every scenario in this feature file.
 
Feature: Simple background feature

Background: Execute before every scenario
  Given I filter some records

Scenario: Verify delete functionality
  Given I click on the delete button of the first record
  Then I verify that record is removed from the table

Scenario: Verify Update functionality
  Given I click on update button of the first record
  Then I verify that record opens in new window and we can modify it

Here is the step definition class.
 
package org.softpost;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;

/**
 * Created by Sagar on 13-07-2016.
 */
public class backgroundsteps {


    @Given("^I filter some records$")
    public void i_filter_some_records() throws Throwable {
        System.out.println("

Background - Filtering some records
");
    }

    @Given("^I click on the delete button of the first record$")
    public void i_click_on_the_delete_button_of_the_first_record() throws Throwable {
        System.out.println("Click delete button
");
    }

    @Then("^I verify that record is removed from the table$")
    public void i_verify_that_record_is_removed_from_the_table() throws Throwable {
        System.out.println("Verify deleted record
");
    }

    @Given("^I click on update button of the first record$")
    public void i_click_on_update_button_of_the_first_record() throws Throwable {
        System.out.println("Click update button
");
    }

    @Then("^I verify that record opens in new window and we can modify it$")
    public void i_verify_that_record_opens_in_new_window_and_we_can_modify_it() throws Throwable {
        System.out.println("Verify modified record
");
    }


}

Here is the output of execution of above feature file.
 
Background – Filtering some records
Click delete button
Verify deleted record

Background – Filtering some records
Click update button
Verify modified record

2 Scenarios (2 passed)
6 Steps (6 passed)
0m0.578s                    

Web development and Automation testing

solutions delivered!!