Install and configure functional testing in Symfony2 using Behat and Mink

The idea that web applications written in PHP need testing is not new and is gradually entering the daily practice of developers. PHPUnit has become the standard for testing PHP applications, including in the new Symfony2 framework. In the installation from symfony-standard to AcmeDemoBundle for testing the controller, it is he who uses 1 . I want to talk about an alternative way of testing functionality using Behat and Mink, and describe the details of the installation and testing process.

Installing the framework


First, we need a working bunch of Apache + PHP 5.3 , with support for local hosts , intl , git . I will not dwell on the process of installing and configuring them - there is enough information on the network how to do this for each individual system, in addition, the developer has already installed all this (I personally think that the development should be done on a local or test machine, and not on a working site)
Next - we will need to download and configure our project from GitHub. Open the terminal, go to the folder where the local sites are located. We check whether your Apache + PHP is suitable for working in Symfony2, for this we use the script supplied with the framework:

$ cd ~/Sites
$ git clone github.com/symfony/symfony-standard.git
$ cd symfony-standard



$ php app/check.php
If you need any settings or modules - install and configure.

Download the framework itself (it is located by default in the vendors folder ). To do this, type in the terminal:
$ php bin/vendors install
After that, you need to configure the project displays in the browser, for which I make changes to two files (your paths may be different, I work on Mac Os 10.6 with the standard apache):
- I add to / etc / hosts a line indicating that my project is local, and there is nothing to look for it on the network: - in /etc/apache2/extra/httpd-vhosts.conf Restart Apache, and check the result of work in the browser by opening the symfony-standard / app_dev.php page . If everything is done correctly, we get the following picture:
...
127.0.0.1 symfony-standard




    DocumentRoot "/Users/Standart-User/Sites/symfony-standard/web"
    ServerName t0002.loc
	
		Options Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
		AllowOverride All
	


Symfony-standard start page

And when you type in the terminal in the root folder of the project,
$ php app/console
we get a list of framework commands. We note for ourselves that the behat command is not yet in this list after listing the Options in the Available commands block.

At this stage, we can assume that we managed to install Symfony2.

Install Mink and Behat for testing


Since all the projects I'm working on are in my ~ / Sites folder and I don’t want to install bundles for testing for each installation of the Symfony2 framework - I did this once in the ~ / Sites / testsuite.behat folder and then connect its contents to your projects.

For ease of installation, I created a project on GitHub, and from there you can install it: In fact, it contains a set of submodules and instructions on how to tie this all up to your working project on Symfony2. After cloning the repository, we need to download the submodules. To do this, we execute the command: Everything, with the installation of the test kit, we are almost done. Since the active branches in Behat and Mink

    $ cd ~/Sites
    $ git clone https://github.com/livsi/testsuite.behat.git
    $ cd testsuite.behat



    $ git submodule update --init


are develop branches, not master - you need to go into them and switch manually.
    $ cd ~/Sites/testsuite.behat/vendor/Behat/Behat/
    $ git checkout --track -b develop origin/develop
    $ cd ~/Sites/testsuite.behat/vendor/Behat/Mink/
    $ git checkout --track -b develop origin/develop


We connect testsuite.behat to the symfony-standart project


This is the fastest stage, since we do not need to get anything from the network, just edit the configuration files in the symfony-standart project . The instructions are attached to the previously downloaded code, located in the README.md file.

Open the ~ / Sites / symfony-standart / app / autoload.php file and add the following lines (you need to correct the paths according to your own) to load the test bundles into the symfony2 project: In the file ~ / Sites / symfony-standart / app / AppKernel.php include two main bundles - BehatBundle and BehatMinkBundle : We write the required parameters in ~ / Sites / symfony-standart / app / config / config_dev.yml :
// app/autoload.php
    $loader->registerNamespaces(array(
    // ...
    'Behat\BehatBundle' => '/Users/Standart-User/Sites/testsuite.behat/vendor',
    'Behat\Behat'       => '/Users/Standart-User/Sites/testsuite.behat/vendor/Behat/Behat/src',
    'Behat\Gherkin'     => '/Users/Standart-User/Sites/testsuite.behat/vendor/Behat/Gherkin/src',
    'Behat\Mink'        => '/Users/Standart-User/Sites/testsuite.behat/vendor/Behat/Mink/src',
    'Behat\MinkBundle'  => '/Users/Standart-User/Sites/testsuite.behat/vendor',
    'Goutte'            => '/Users/Standart-User/Sites/testsuite.behat/vendor/Goutte/src',
    'Zend'              => '/Users/Standart-User/Sites/testsuite.behat/vendor/Zend/library',
    'Behat\SahiClient'  => '/Users/Standart-User/Sites/testsuite.behat/vendor/Behat/SahiClient/src',
    'Buzz'              => '/Users/Standart-User/Sites/testsuite.behat/vendor/Buzz/lib',
// ...


// app/AppKernel.php
    if (in_array($this->getEnvironment(), array('dev', 'test'))) {
    // ...
    $bundles[] = new Behat\BehatBundle\BehatBundle();
    $bundles[] = new Behat\MinkBundle\BehatMinkBundle();
    // ...
    }


# app/config/config_dev.yml
framework:
    test:       ~
# ...
behat: ~
behat_mink:
    base_url:  http://symfony-standart/app_test.php/
    goutte:     ~   # enable both Goutte
    sahi:       ~   # and Sahi session

We check that everything is installed and configured correctly, for this, from the root of the symfony-standart project in the terminal, enter:
$ php app/console
we get a list of commands from the framework, in which the behat command should now be present . This means that everything works and the necessary bundles are connected.

Testing itself



To create a testing framework for the bundle, we execute the command in the console from the project root:
$ php app/console behat:bundle --init Acme\\DemoBundle
It creates the Features directory in the src / Acme / DemoBundle folder /

Add a file to it, which we will call feature1.feature with the following content: These are the very same functional tests. To run the test, we enter the command in the console: and we see approximately the following result: From the screenshot you can see that the call syntax has been simplified: first from behat: test: bundle to behat: bundle , and now to just behat . Help on the necessary keys for the console command can be obtained by typing

# language: ru
Функционал: Первый тест для AcmeDemoBundle
  Тестируем реализованные возможности в демонстрационном бандле
  Сценарий: Открыть главную страницу в dev окружении и убедиться в ее существовании
    Допустим я на странице "/app_dev.php"
    Тогда код ответа сервера должен быть 200
    И я должен видеть "Congratulations! You have successfully installed a new Symfony application."
    И я должен видеть "Welcome!"
  Сценарий: Перейти с главной страницы на страницу по ссылке "Run The Demo"
    Допустим я на странице "/app_dev.php"
    Если я кликаю по ссылке "Run The Demo"
    Тогда я на странице "/app_dev.php/demo/"
    И код ответа сервера должен быть 200
    И я должен видеть "Available demos" 



$ php app/console behat --no-paths @AcmeDemoBundle
AcmeDemoBundle symfony-standard test result




app/console help behat

Having spent relatively little time connecting Behat and Mink, we get a significant profit in the form of simple and readable, visual tests that are written in a clear language. They are quickly written and quickly executed.

Acknowledgments


Special thanks to Konstantin Kudryashov (everzet habrayuzer ) for creating Behat and Mink , advising on their use, KnpLabs for sponsorship and assistance to their author, for supporting the project and its further improvement.
Also many thanks to the developers of Symfony2 for a powerful and convenient framework, and the most detailed documentation that helps to quickly master it.

Materials and repositories used:






An example of testing a controller using PHPUnit (used by default in symfony2): The same with Behat. Isn't it - the Behat test is more visual?

namespace Acme\DemoBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DemoControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = $this->createClient();
        $crawler = $client->request('GET', '/demo/hello/Fabien');
        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}



  Сценарий: Повторяем тест контроллера, проводимого через PHPUnit
    Допустим я на странице "/app_dev.php/demo/hello/Fabien"
    Тогда я должен видеть "Hello Fabien"



Also popular now: