Functional testing with Behat in laravel 5.1

 

After running the composer update, Behat’s functionality is added to Laravel. Next, a behat.yaml file should be added to the root of the Laravel project to specify which extensions are to be used.

Next, run the following command:

$ behat --init

This will create a features directory with a bootstrap directory inside it. A FeaturesContext class will also be created. Everything inside bootstrap will be run every time behat is run. This is useful to automatically run migrations and seeding.

The features/bootstrap/FeaturesContext.php file looks like this:

<?php

use BehatBehatContextContext;
use BehatBehatContextSnippetAcceptingContext;
use BehatGherkinNodePyStringNode;
use BehatGherkinNodeTableNode;

/**
 * Defines application features from the specific context.
 */
class FeatureContext implements Context, SnippetAcceptingContext
{
    /**
     * Initializes context.
     *
     * Every scenario gets its own context instance.
     * You can also pass arbitrary arguments to the
     * context constructor through behat.yml.
     */
    public function __construct()
    {
    }
}

Next, the FeatureContext class needs to extend the MinkContext class, so the class definition line will need to be modified as follows:

class FeatureContext implements Context, SnippetAcceptingContext

Next, the prepare and cleanup methods will be added to the class in order to perform the migrations. We will add the @BeforeSuite and @AfterSuite annotations to tell Behat to perform the migration and seeding before each suite and migrate to rollback in order to restore the database to its original state after each suite. Using annotations in the doc-block will be discussed , Taming Complexity with Annotations. Our class now is structured as follows:

<?php

use BehatBehatContextContext;
use BehatBehatContextSnippetAcceptingContext;
use BehatGherkinNodePyStringNode;
use BehatGherkinNodeTableNode;

/**
 * Defines application features from the specific context.
 */
class FeatureContext implements Context, SnippetAcceptingContext
{
    /**
     * Initializes context.
     *
     * Every scenario gets its own context instance.
     * You can also pass arbitrary arguments to the
     * context constructor through behat.yml.
     */
    public function __construct()
    {
    }
     /**
     * @BeforeSuite
     */
     public static function prepare(SuiteEvent $event)
     {
        Artisan::call('migrate');
        Artisan::call('db:seed');

     }

     /**
     * @AfterSuite 
     */
     public function cleanup(ScenarioEvent $event)
     {
        Artisan::call('migrate:rollback');
     }
}

 

Chapter 2 of 8

Comments

Pin It on Pinterest

Shares