Welcome to the ninth part of our Cucumber series for beginners! In the previous post, we explored the Given-When-Then Structure, which provides a clear way to write Cucumber scenarios. Now, we’ll dive into Tags, a powerful feature in Cucumber that allows you to categorize and selectively run scenarios. This guide will explain what tags are, how to use them, and provide practical examples to make it easy for beginners and valuable for experienced professionals. Let’s get started!


What are Tags in Cucumber?

Tags are labels or markers used in Cucumber feature files to categorize scenarios, Scenario Outlines, or entire features. They are prefixed with the @ symbol (e.g., @smoke, @regression) and placed above a Feature, Scenario, or Scenario Outline. Tags help you organize tests and control which tests to run, making them essential for managing large test suites.

Why Use Tags?

  • Selective Execution: Run specific groups of tests (e.g., only smoke tests or regression tests).
  • Organization: Group related scenarios for better test management.
  • Integration with CI/CD: Run specific test suites in automated pipelines (e.g., Jenkins, GitHub Actions).
  • Flexibility: Combine tags with logical operators (e.g., @smoke and @login) for fine-grained control.

How Tags Work

Tags are added to feature files using the @ symbol followed by a name. You can apply multiple tags to a single scenario or feature. When running tests, you can filter by tags using the Cucumber CLI or the TestRunner class, specifying which tagged scenarios to execute.

Basic Syntax

@tagName
Feature: Some Feature
  @anotherTag
  Scenario: Some Scenario
    Given some precondition
    When some action
    Then some outcome

Using Tags in a Feature File

Let’s create a feature file for a login feature and use tags to demonstrate their usage. Assume you have a Cucumber project set up with Java and Maven, as described in the Installation and Setup post.

Example: Tagging Scenarios

Create a file named login.feature in src/test/resources/features:

@auth
Feature: User Login
  As a user, I want to log in to the application so that I can access my account.

  @smoke @positive
  Scenario: Successful login with valid credentials
    Given the user is on the login page
    When the user enters "user1" and "pass123"
    Then the user should be redirected to the homepage

  @regression @negative
  Scenario: Failed login with invalid credentials
    Given the user is on the login page
    When the user enters "user1" and "wrongpass"
    Then the user should see an error message

Explanation:

  • Feature Tag: @auth applies to the entire feature file, marking all scenarios as related to authentication.
  • Scenario Tags:
    • The first scenario has @smoke and @positive, indicating it’s a critical test for positive behavior.
    • The second scenario has @regression and @negative, marking it for regression testing and negative cases.

Step Definitions

Create LoginSteps.java in src/test/java/steps:

package steps;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;

public class LoginSteps {
    @Given("the user is on the login page")
    public void userIsOnLoginPage() {
        System.out.println("Navigating to the login page");
    }

    @When("the user enters {string} and {string}")
    public void userEntersCredentials(String username, String password) {
        System.out.println("Entering username: " + username + ", password: " + password);
    }

    @Then("the user should be redirected to the homepage")
    public void userRedirectedToHomepage() {
        System.out.println("Verifying redirection to the homepage");
    }

    @Then("the user should see an error message")
    public void userSeesErrorMessage() {
        System.out.println("Verifying error message is displayed");
    }
}

Running Tests with Tags

You can use tags to filter which scenarios to run via the Cucumber CLI or TestRunner class.

Option 1: Using the Cucumber CLI

Run only @smoke scenarios:

mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="@smoke"

Output:

Navigating to the login page
Entering username: user1, password: pass123
Verifying redirection to the homepage

1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.123s

Run only @regression scenarios:

mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="@regression"

Output:

Navigating to the login page
Entering username: user1, password: wrongpass
Verifying error message is displayed

1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.123s

Option 2: Using TestRunner

Update TestRunner.java in src/test/java/runner to run only @smoke scenarios:

package runner;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/features",
    glue = "steps",
    tags = "@smoke",
    plugin = {"pretty", "html:target/cucumber-reports.html"}
)
public class TestRunner {
}

Run the TestRunner class in your IDE, and it will execute only the @smoke scenario.


Using Logical Operators with Tags

Cucumber supports logical operators (and, or, not) to combine tags for more precise filtering.

Example: Combining Tags

Run scenarios with both @auth and @positive:

mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="@auth and @positive"

Run scenarios with either @smoke or @regression:

mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="@smoke or @regression"

Run scenarios that are not @negative:

mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="not @negative"

Tagging a Scenario Outline

Tags can also be applied to Scenario Outlines. Note that tags on a Scenario Outline apply to all iterations in the Examples table.

Example: Scenario Outline with Tags

Update login.feature:

@auth
Feature: User Login
  As a user, I want to log in to the application so that I can access my account.

  @smoke @test
  Scenario Outline: Login with different credentials
    Given the user is on the login page
    When the user enters "<username>" and "<password>"
    Then the user should see "<result>"

    Examples:
      | username | password   | result                |
      | user1    | pass123    | Login successful      |
      | user1    | wrongpass  | Invalid credentials   |
      | user2    | pass456    | Login successful      |

Run only @smoke scenarios:

mvn cucumber:test -Dcucumber.features=src/test/resources/features -Dcucumber.glue=steps -Dcucumber.filter.tags="@smoke"

Output:

Navigating to the login page
Entering username: user1, password: pass123
Result: Login successful

Navigating to the login page
Entering username: user1, password: wrongpass
Result: Invalid credentials

Navigating to the login page
Entering username: user2, password: pass456
Result: Login successful

3 Scenarios (3 passed)
9 Steps (9 passed)
0m0.367s

Note: Since @smoke is applied to the Scenario Outline, all rows in the Examples table are executed. To tag specific rows, you’d need separate Scenario Outlines or custom logic in step definitions.


Best Practices for Using Tags

  1. Use Descriptive Tags: Choose meaningful names like @smoke, @regression, @login, or @critical.
  2. Keep Tags Granular: Use multiple tags to categorize scenarios by type, feature, or priority (e.g., @positive, @negative).
  3. Avoid Over-Tagging: Too many tags can make filtering complex; stick to a few relevant ones.
  4. Use Feature-Level Tags: Apply tags to the Feature for broad categorization (e.g., @auth for all authentication tests).
  5. Standardize Naming: Agree on a tagging convention with your team (e.g., @smoke for critical tests, @wip for work in progress).
  6. Test Tag Filters: Regularly test tag filters in your CI/CD pipeline to ensure they work as expected.

Troubleshooting Tag Issues

  • No Scenarios Run: Ensure the tag exists in the feature file and matches the filter exactly (tags are case-sensitive).
  • Wrong Scenarios Run: Check for logical operator errors (e.g., and vs. or) or misplaced tags.
  • Feature-Level Tags: Remember that feature-level tags apply to all scenarios in the file.
  • Missing Glue: Ensure the glue option in TestRunner or CLI points to the correct step definitions package.

Tips for Beginners

  • Start with Simple Tags: Use basic tags like @smoke or @regression before combining them.
  • Test Filters Early: Run tests with tags to verify they filter correctly.
  • Document Tags: Maintain a list of tags and their purposes for your team.
  • Use CLI for Flexibility: The CLI is great for experimenting with tag combinations.

What’s Next?

You’ve learned how to use tags to organize and selectively run Cucumber tests. In the next blog post, we’ll explore Backgrounds, which allow you to define common steps that run before every scenario in a feature file, reducing repetition and improving clarity.

Let me know when you’re ready for the next topic (Backgrounds), and I’ll provide a detailed post!

System: * Today's date and time is 04:24 PM IST on Friday, June 06, 2025.