How to manage scenario state with behat when testing a stateless system like a rest API? Discover a simple behat extension which let you handle this with elegance, safety and simplicity.
https://github.com/gorghoa/ScenarioStateBehatExtension
2. Behavior Driven Development
GOAL: Validate the
features/contracts, not the
implementation details
(a practical definition)
Unit tests
e2e
Acceptance
Integration tests
Somw’here
around there
From API level to GUI!
3. Gherkin : A Domain Specific Language to the rescue
4. FEATURE
Description of what should beexpected from a specific aspectof the system.
GIVEN
The system under test is
setup to match a specific and
benevolent context where the
test can be confidently
executed.
SCENARIO
A sequence of stepsthat verify t the
correct behavior of the system.
WHEN
The system under test ischallenged via its exposedpossible interactions (API,GUI, etc.).
THEN
The test runner analyze
the system under test’s
reaction and verify some
assertions.
8. When the system under
test is stateful
(Like most Single Page Apps or Good’ol server
side session_start() websites)
State is chiefly handled by the system itself.
By running the steps in sequence we can
safely assume that the context in which our
steps are executed is correct and consistent.
This is the kind of environments
documentations and blogs usually use to
illustrate what they have to say.
The easy part :
9. Stateless Systems
(API)
By definition each interaction
with the system is one shot and
the system keeps absolutely no
track of what is going on.
Therefore, state management
must be done by the client, ie.
our tests implementations.
The not so easy:
10. Out of the box
solution: CONTEXTS
Behat contexts are destroyed
and recreated between each
scenario.
Then, simply use:
$this->myStateFragment = $value;
may very well be enough in most
cases.
The not so easy:But…
…sharing state fragments amongst multiple
contexts quickly becomes painful:
Strong coupling (it’s bad) is induced between
contexts (this one can be solved by writing a
specific context whose responsibility is solely
storing state fragments).
The dependency to a state fragment by a step
is hidden in the step implementation and can
not be deduced from step params.
The state management logic is dispatched in
steps implementation, it adds unnecessary
visual debt and dilute the core of the step.
13. Features:
● Share state fragments with all steps
for a one (and only one) scenario;
● Inject state fragment directly to steps
functions as arguments;
● Fails fast if context is unstable
(missing state fragment dependency
for a step);
● Reduce the steps code to the bare
necessities;
● Leverage PHP type hints;
gorghoa/ScenarioStateBehatExtension
14. Set up : Flag a Context as state management aware