Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandresalome/1012988 to your computer and use it in GitHub Desktop.
Save alexandresalome/1012988 to your computer and use it in GitHub Desktop.
Explaining why classes are not possible in Behat as step definitions
<?php
/*
You can't use classes like this to define steps by the simple reason:
in Behat and Cucumber, step definitions and test contexts ARE two
splitted logical elements, not one. Different step definitions
can be used together in different scenarios and each scenario will
have it's own context (environment) object. That's the main logical
idea behind Behat - define step once - use it everywhere.
What you've done with this example - you've tied single step
definitions collection to environment. You've made scenario context
by hands. And you WILL MUST create such contexts FOR EVERY scenario.
That's insane.
2 bad things happened here:
1) from now on, you can't split definitions in different files,
different directories or even use predefined definitions from multiple
sources (inheritance woun't work, cuz there's context also).
2) from now on, you can't easily extend environment with your own logic
or extend context logic from different sources, cuz context now tied
to YOUR steps (inheritance woun't work, cuz there's definitions also).
Behat is based on 2 main concepts:
1) global step definitions collection
2) local context for every scenario, that gets used inside steps
When you'll find a way to do it with PHP classes - call me.
*/
class CalcSteps
{
protected $calc;
protected $screen;
public function start()
{
$this->calc = new Calc();
}
public function getSteps()
{
return array(
'/I start the calculator' => array($this, 'start'),
'/I have entered (.*) in the calculator' => array($this, 'enterValue'),
'/I press add' => array($this, 'pressAdd'),
'/The result should be (.*) on the screen/' => array('resultShouldBe')
);
}
public function pressAdd()
{
$this->screen = $this->calc->getSum();
}
public function enterValue($value)
{
$this->calc->add($value);
}
public function resultShouldBe($value)
{
assertEquals($value, $this->screen);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment