Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Hooks and Tags

Sharing State: World and Dependency Injection

Share state between Cucumber step definition classes safely: one object per scenario, the World in Cucumber.js, PicoContainer and Spring injection, and why static fields break tests.

A scenario is a story told in several steps, and the steps need to pass information along. The Given creates a customer, the When places an order for that customer, and the Then checks the order's total. Each step is a separate method, perhaps in a separate class, so where does the customer live between steps?

The wrong answer is a static field or a global variable. The right answer is a small object whose lifetime is exactly one scenario, handed to every class that needs it. This lesson explains the idea, shows how Cucumber-JVM (PicoContainer and Spring), Cucumber.js and Ruby provide it, and gives a runnable Java stand-in of an injection container so you can see why it works. The real frameworks cannot run on this site, so their code is read-only.

The rule: one fresh object per scenario

Cucumber creates new instances of your step definition classes for every scenario. That alone means ordinary instance fields are safe inside one class: the next scenario will get a new object with empty fields. Trouble starts when two step classes need the same data, because they are two separate objects.

Java
public class CustomerSteps {
    private Customer customer;          // visible only in this class

    @Given("a customer named {word}")
    public void aCustomer(String name) {
        customer = new Customer(name);
    }
}

public class OrderSteps {
    @When("she orders {int} books")
    public void order(int count) {
        // How do we reach the customer created in CustomerSteps?
    }
}

A static field would "work", but it survives between scenarios, so one scenario can leak data into the next, and parallel runs corrupt each other. See Parallel execution.

Dependency injection

The idiomatic fix is to put shared state in its own plain class and ask for it in the constructor. The DI container creates one instance per scenario and passes the same instance to every class that asks.

Java
public class ShopWorld {                 // plain class, no annotations
    public Customer customer;
    public Order order;
}

public class CustomerSteps {
    private final ShopWorld world;

    public CustomerSteps(ShopWorld world) {   // injected by the container
        this.world = world;
    }

    @Given("a customer named {word}")
    public void aCustomer(String name) {
        world.customer = new Customer(name);
    }
}

public class OrderSteps {
    private final ShopWorld world;

    public OrderSteps(ShopWorld world) {
        this.world = world;
    }

    @When("she orders {int} books")
    public void order(int count) {
        world.order = world.customer.order(count);
    }
}

Hooks live in classes too, so they can receive the same object, and a @Before hook can fill it, or an @After hook can read it to clean up.

Run the stand-in container. It builds a new ShopWorld per scenario and wires it into two step classes through their constructors, using reflection like the real thing does.

Java A tiny injection container (Java stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second scenario shows one book, not four. That clean start is the whole point.

What the real containers add

  • PicoContainer (cucumber-picocontainer): add the dependency and nothing else. Any class with a public constructor that takes other classes becomes injectable. It is the simplest choice for new projects.
  • Spring (cucumber-spring): mark one class with @CucumberContextConfiguration and @SpringBootTest (or @ContextConfiguration), and inject beans normally. Scope state beans with @ScenarioScope (from io.cucumber.spring) so each scenario receives its own copy.
  • Guice, Weld, OpenEJB, Needle are alternatives; pick one container per project, because Cucumber-JVM allows only one object factory.
Java
@CucumberContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CucumberSpringConfiguration { }

@Component
@ScenarioScope
public class ShopWorld {
    public Customer customer;
}

The World in other languages

In Cucumber.js the shared object is the World. Step functions use this (so they must be function, not arrow functions):

JavaScript
const { setWorldConstructor, Given, When, Then } = require('@cucumber/cucumber');

class ShopWorld {
  constructor() { this.customer = null; this.books = 0; }
}
setWorldConstructor(ShopWorld);

Given('a customer named {word}', function (name) { this.customer = name; });
When('she orders {int} books', function (n) { this.books += n; });

In Ruby the World is the object the steps run in; you extend it with modules: World(ShopHelpers), and instance variables such as @customer are shared between steps of one scenario. The same one-fresh-world-per-scenario rule holds in all three.

Here is the JavaScript idea, runnable, in the browser console editor.

JS One World per scenario (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Design advice

  • Keep the shared class small and about the domain: customer, cart, lastResponse. Do not turn it into a bag of everything.
  • Put behavior in collaborators (a ShopApi, a page object) and let the world only carry references to them. See Page objects.
  • Share objects, not primitives, when two classes update the same value.
  • Never share state between scenarios on purpose. If you need slow, read-only data, build it once in @BeforeAll (hooks) and treat it as immutable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a static field a bad way to share state between steps?

    A static field lives for the whole run, so one scenario can leak data into the next, and parallel scenarios overwrite each other.
  2. 2. How does PicoContainer know what to pass to a step class constructor?

    It looks at the constructor parameter types and creates or reuses one instance of each for the scenario.
  3. 3. In Cucumber.js, why must steps that use the World be written as regular functions?

    Cucumber.js calls the function with the World as this. An arrow function keeps the surrounding this instead.
  4. 4. Which annotation gives each scenario its own copy of a Spring bean?

    @ScenarioScope from io.cucumber.spring creates one bean instance per scenario.

Summary

  • Cucumber builds new step classes for each scenario; share state through an injected per-scenario object.
  • PicoContainer needs only a dependency; Spring needs a configuration class and @ScenarioScope.
  • Cucumber.js and Ruby use a World object with the same lifetime.
  • Avoid static fields and global variables; keep the shared class small.

Next: Test data setup and cleanup