LoginSignup
0
0

More than 5 years have passed since last update.

認証が必要なコントローラークラスをテストする

Posted at

コントローラークラスのテスト

CakePHPではIntegrationTestCaseクラスを使うとコントローラーを通したテストができる。複数のクラスが連動した動きになるので、WebIFレベルのテストが可能になる

基本

認証が必要ないアクションのテスト
http://<domain>/articlesにGETメソッドを送信

class ArticlesControllerTest extends IntegrationTestCase
{
    public $fixtures = ['app.articles'];

    public function testIndex()
    {
        $this->get('/articles');
        $this->assertResponseOk();
    }
}

同じような使い方で各種HTTPメソッドをリクエストすることができる。
HTTPボディ部があるメソッドの場合は第二引数で連想配列を設定する。

認証が必要なアクションのテスト

CakePHPのAuthComponentを使った認証を実装している場合、HTTPリクエストの送信前に以下をテストメソッド内で設定する。
※但し、フィクスチャ(テスト時に利用されるDBのダミーデータ)にid=1のユーザーが存在している必要がある。

    public function testIndex()
    {
        $this->session([
            'Auth' => [
                'User' => [
                    'id' => 1,
                ],
            ],
        ]);
        $this->get('/articles');
        $this->assertResponseOk();
    }

AuthComponentの補足

デフォルトでUsersTableの情報を認証情報のデータとして扱うため、上記でUserを指定している。
異なるテーブルを認証情報としている場合、Userを異なるモデル名に変更すれば行ける。多分。

CSRF対策をしているアクションのテスト

CakePHPのCSRFを利用している場合、テストメソッド内で以下を設定する。

    public function testIndex()
    {
        $this->enableCsrfToken();
        $this->get('/articles');
        $this->assertResponseOk();
    }

認証+CSRF対策をしているアクションのテスト

これまでの話をまとめて。

    public function testIndex()
    {
        $this->enableCsrfToken();
        $this->session([
            'Auth' => [
                'User' => [
                    'id' => 1,
                ],
            ],
        ]);
        $this->get('/articles');
        $this->assertResponseOk();
    }

所感

便利なものはだいたい用意されてるので楽ですね。
WebIFベースでTDDしても効率良くないかも。PHPUnit見てもモデル原因のエラーは分からない事が多い。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0