LoginSignup
2
4

More than 3 years have passed since last update.

Route Model Bindingしているルートに対してテストするときのコツ

Posted at

HTTPテストを書くとき
ミドルウェアを無効化したほうが都合がいい時があるかと思います
(公式: https://readouble.com/laravel/5.1/ja/testing.html#disabling-middleware )

そんなとき
use WithoutMiddleware;
とかしてミドルウェアを全部無効化しちゃうという対応をされることも珍しくないと思います。

ですが、これが
Route Model Bindingしているルートに対してHTTPテスト
となると、ひと手間必要だったのでメモっときます

Route Model Bindingしているルートに対してHTTPテストを書くとき

route('user.update', $user->id)
web.phpにて

Route::patch('{user}/update', 'UserController@update');

と定義されたルートであることを仮定します

順当に書くとしたら


    use WithoutMiddleware;

    public function testUpdate()
    {
        $user = User::find(1);
        $response = $this->actingAs($user)
            ->patch(route('user.update', $user->id), ['name' => 'taro' ]);
    }

こうなんですが、これだとRoute Model Bindingされません

Route Model Binding自体が何かしらのmiddlewareを使って機能しているからだ、と思われます

なので最小限のミドルウェアのみを無効化して対応しましょう


    use WithoutMiddleware;

    public function testUpdate()
    {
        // ルートモデルバインディングをしているので、対応するため無効化するミドルウェアを最小限にする
        $this->withMiddleware();
        $this->withoutMiddleware([VerifyCsrfToken::class, Authenticate::class]);

        $user = User::find(1);
        $response = $this->actingAs($user)
            ->patch(route('user.update', $user->id), ['name' => 'taro' ]);
    }

参考: https://github.com/laravel/framework/issues/16260

2
4
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
2
4