How do I test the Behat context?

Behat is a very good tool, BDD / TDD / DDD is IMHO - the core of FIRM coding, but ...

I often see projects using Behat with rather complex context classes that are NOT tested.

For example: Sylius / TaxonomyContext or Sylius / ProductContext

 * @Given /^taxonomy "([^""]*)" has following taxons:$/
public function taxonomyHasFollowingTaxons($taxonomyName, TableNode $taxonsTable)
    $taxonomy = $this->findOneByName('taxonomy', $taxonomyName);
    $manager = $this->getEntityManager();
    $taxons = array();
    foreach ($taxonsTable->getRows() as $node) {
        $taxonList = explode('>', $node[0]);
        $parent = null;
        foreach ($taxonList as $taxonName) {
            $taxonName = trim($taxonName);
            if (!isset($taxons[$taxonName])) {
                /* @var $taxon TaxonInterface */
                $taxon = $this->getRepository('taxon')->createNew();
                $taxons[$taxonName] = $taxon;
            $taxon = $taxons[$taxonName];
            if (null !== $parent) {
            } else {
            $parent = $taxon;


This example is not "rocket science", but it has quite a few places that it could not work in. From my experience, Behat Contexts can get quite complex.

Should I also "trust" my contexts so much and assume that they work 100% correctly? Or is there a guide / tutorial on how I can test Behat Contexts?

What do you do? How do you do this?


source to share

1 answer

I would say it depends on how you create your test suite.

How Behat is the basis for creating your own test suite, and since this is the software to be created, software development best practices should be considered. One of them is the MVC concept. In Behat, Contexts are "controllers" and don't need to contain much logic. Ideally, they should call the required methods in the underlying services, which will provide the basic functionality.

Of course, for simple out-of-the-box steps (e.g. due to Mink extensions, etc.) it is quite easy to create multiple tests, while for more complex logic, I would recommend creating a service that handles super heavy logic, validations, etc. ... This way, you can test the sandboxed service from all angles while keeping your "control" context clean and simple.

On the other hand, if you can design your test without involving a lot of hidden logic (since tests should be as open and clean as possible), you don't need any service, and simple sentences should be enough. Then, if you really care about your quality, you can create some minor tests.

For complex cases like the example above, I will try to encapsulate some code in a service / dispatcher and leave a simple controller without any tests, while still providing broad testing coverage for the underlying services.



All Articles