Behat/Mink 用のオレオレコンテキストを作った時に、たとえばエラーになるべきとこでエラーになるかとか、そういうのを phpspec で確認する方法。
テストのためのテストってなんだか無限ループな感じですが、汎用的なエクステンションを作ってて、そのためにテストをしたいのです。
前提条件
Behat の WebDriver には以下の2種類を使う。
- Goutte
- Selenium2
テスト対象のコード
この記事では以下のようなコンテキストがあることを想定しています。
/**
* Check http status code.
* Example: the HTTP status should be 400
*
* @param string $expect The HTTP status code.
* @then /^the HTTP status should be (?P<expect>[0-9]+)$/
*/
public function the_http_status_should_be( $expect )
{
$status = $this->getSession() ->getStatusCode();
$this->assertSame( $status, intval( $expect ), sprintf(
'The HTTP status is %1$s, but it should be %2$s',
$status,
$expect
) );
}
*.feature
に以下のような感じの記述をして期待通りのステータスコードが戻ってくるかを確認するためのコンテキストです。
Scenario: Check http status code
When I am on "/"
Then the HTTP status should be 200
When I am on "/the-page-not-found"
Then the HTTP status should be 404
Spec ファイルの記述
以下のテストは、本来 200 であるはずの URL にアクセスした時に 404 であるべきと指定したら例外が戻ってくるかを確認しています。
<?php
namespace spec\VCCW\Behat\Mink\MyExtension\Context;
use PhpSpec\ObjectBehavior;
use Behat\Mink\Mink,
Behat\Mink\Session,
Behat\Mink\Driver\GoutteDriver,
Behat\Mink\Driver\Goutte\Client as GoutteClient,
Behat\Mink\Driver\Selenium2Driver;
class RawMyContextSpec extends ObjectBehavior
{
public function it_should_return_exception()
{
$this->init_mink( 'goutte' );
$session = $this->getSession();
$session->visit( 'http://127.0.0.1:8080/' );
$message = 'The HTTP status is 200, but it should be 404';
$this->shouldThrow( new \Exception( $message ) )->during(
'the_http_status_should_be',
array( 404 )
);
}
private function init_mink( $driver )
{
$mink = new Mink( array(
'goutte' => new Session( new GoutteDriver( new GoutteClient() ) ),
'selenium2' => new Session( new Selenium2Driver() ),
) );
$mink->setDefaultSessionName( $driver );
$this->setMink( $mink );
}
}
ポイント
-
init_mink()
メソッドで Mink インスタンスを作成する。 -
init_mink
の引数 $driver で、どのドライバーを使用するかを指定する。
Mink とかそのドライバーのドキュメントを読めばなんだそんなことかって感じだったんですが、数ヶ月前に挑戦してその時はあきらめたので、やっとできてよかった。