Running individual scenarios in JBehave or Cucumber with Serenity BDD

John Ferguson Smart | Mentor | Author | Speaker - Author of 'BDD in Action'.
Helping teams deliver more valuable software sooner2nd November 2017

JBehave | Requirements Discovery | Xscale |

When we are working with BDD test automation tools such as Cucumber and JBehave, it often comes in handy to run an individual scenario in isolation. In this article, we look at how to do this using Serenity BDD.

JBehave

In JBehave, you need to use tags to identify the scenario you want to run. For example, suppose we want to use the @current tag to flag the individual scenario(s) we want to run. First, we write a simple runner class like the following:

import net.serenitybdd.jbehave.SerenityStories;
import net.serenitybdd.jbehave.annotations.Metafilter;

@Metafilter("+current")
public class RunASingleScenario extends SerenityStories {}

Note the @Metafilter annotation? That's where we tell JBehave to only run scenarios with the @current tag.

Next, we add the tag to the scenario(s), in the Meta: section underneath the Scenario heading, as shown below:

Adding and subtracting

Scenario: A scenario with before and after phases
Meta:
@current
Given I have a calculator
And I add 1
When I add 2
Then the total should be 3

Scenario: Another scenario with before and after phases
Given I have a calculator
And I add 1
When I add 3
Then the total should be 4

Cucumber

In Cucumber, you can use a similar approach. The equivalent runner class in Cucumber would look like this:

import cucumber.api.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features="src/test/resources/features", tags = "@current")
public class RunASingleScenario {}

Then, just add the tag before the Scenario heading, as shown here:

Feature: Adding and subtracting

@current
Scenario: A scenario with before and after phases
Given I have a calculator
And I add 1
When I add 2
Then the total should be 3

Scenario: Another scenario with before and after phases
Given I have a calculator
And I add 1
When I add 3
Then the total should be 4

Running scenarios from the command line

The only problem with using tags is that you need to modify your feature files each time you want to run a different scenario. Cucumber (but not JBehave) does give you another option, however. You can refer to a scenario in a feature file using it's path and the line number the scenario starts at. For example, to run the second scenario from the previous feature file, we could run the following from the command line:

$ mvn clean verify -Dcucumber.options="classpath:features/calculators/adding_and_subtracting.feature:10"

This approach is a little long-winded, and you need to make sure you quote the right line number, but it does avoid having to modify the source code.

© 2019 John Ferguson Smart