Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@pinekta

Laravelのテストでcookieを設定したはずなのに取得できない場合

More than 1 year has passed since last update.

Controllerのテストで設定されたcookieの値で処理を分岐させる箇所があったので、
cookieを設定したものの、Controller側ではnullになってしまって取得できなくてハマってしまったので誰かのためにいつか役に立つことを願いつつメモします。

環境

名前 バージョン
PHP 7.2.6
Laravel 5.5.40

事象

cookieが取得できなかったときのコードは以下です。

ExampleControllerTest.php
    public function testIndex()
    {
        $response = $this->call(
            'GET',
            '/',
            [],
            ['cookie-name' => 'cookie-value']
        );
        $response->assertStatus(200);
    }
ExampleController.php
    public function index(Request $request)
    {
        $cookie = \Cookie::get('cookie-name');

        if (is_null($cookie)) {
            dump('cookieはnullです。');
            return response('', 400);
        }

        return response('', 200);
    }

テストを実行するとcookieがnullになっています。
どうすればいいのでしょうか?

解決法

Laravelはミドルウェアでcookieを自動的に暗号化しますので、
テストのときだけ暗号化を無効にします。

ExampleControllerTest.php
    public function testIndex()
    {
        // テストでcookieが利用できるように暗号化対象から除外
        $this->disableCookiesEncryption(['cookie-name']);

        $response = $this->call(
            'GET',
            '/',
            [],
            ['cookie-name' => 'cookie-value']
        );
        $response->assertStatus(200);
    }

    protected function disableCookiesEncryption($cookies)
    {
        $this->app->resolving(App\Http\Middleware\EncryptCookies::class, function ($object) use ($cookies) {
            $object->disableFor($cookies);
        });

        return $this;
    }

これでController側でcookieが取得できるようになります。

参考

[5.2] Cookies sent in test are not present in request.

3
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
pinekta

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
3
Help us understand the problem. What is going on with this article?