Describing Web API with Behat *.feature(s)

Published on

Jan 2, 2012

how2tips

Jan 3, 2012 − "Can we test Web API of our website with Behat?". We hear this question alot in Behat user group, twitter and emails. Although it's not so complex task as web UI testing (say hello to Mink), it still raises some question, that we will try to answer today.

"Can we test Web API of our website with Behat?". We hear this question alot in Behat user group, twitter and emails. Although it's not so complex task as web UI testing (say hello to Mink), it still raises some question, that we will try to answer today.

First, some theory. Some of you may thought to use Mink for web API testing. Don't! Though tasks might look similar, they are very different by nature of their obersvers. With Mink, you're describing your website UI from the user behind browser point of view. And when you're talking bout web API testing - you always describing scenarios from API user (computer programm, developer) point of view.

Mink tries to simulate everything usual user can do with your site through his browser, including opening web pages, clicking links, filling forms, but excluding reading of response status codes, HTTP headers and parsing JSON responses - this is a crawler tasks. And for crawler tasks you should use real crawler, not browser emulator.

Buzz

So, now we know that we need to use crawler, but where to get one? The good news is that Symfony community already has amazing crawler, written by very famous Kris Wallsmith. The only thing we need is to write API steps definitions, which will use this cool library. You know what? We've already have done it for you.

Setup

To install Behat with common contexts and buzz, we will use Packagist. Move to your project folder and create there composer.json file with:

{
    "require": {
        "behat/behat":           ">=2.2.2",
        "behat/common-contexts": "*",
        "kriswallsmith/buzz":    ">=0.5"
    },

    "config": { "bin-dir": "bin/" }
}

Now just call:

$ wget -nc http://getcomposer.org/composer.phar
$ php composer.phar install

Composer will install Behat, CommonContexts and Buzz into vendor/ folder and will link behat executable into vendor/bin/ folder.

Lets create our FeatureContext:

$ bin/behat --init

and use WebApiContext as subcontext inside its constructor:

public function __construct(array $parameters)
{
    $this->useContext('api',
        new BehatCommonContextsWebApiContext($parameters['base_url'])
    );
}

No need to require something or configure autoloader. Composer have done all this for you behind the scene - automatically.

Now, to check that everything works as expected, lets list all available commands:

$ bin/behat -di

That's it for today. You can see extended example on github.

Written by

KNP Labs
KNP Labs

Comments