コントローラーのとあるメソッドのテストを書いていたら、意外なところではまってしまったのでメモ。
テスト対象コード
リクエストデータから’destination’を取得し、データをごにゃごにゃしてjsonで返すメソッドです。
public function getWeather(Request $request)
{
$destination = $request->destination;
//略 リクエストを元にデータ取得
return response()->json(
[
'data' => $weather_array['weather'][0]['main'],
'icon' => $weather_array['weather'][0]['icon'],
]
);
}
だめだったテスト
最初こんな風にテストを書いていました。
/**
* @test
* @covers \App\Controllers\Api\TwitterController::getWeather
*/
public function getWeather()
{
$data = ['destination' => '東京'];
$response = $this->get('api/weather', $data);
$response->assertStatus(200);
}
phpunitを走らせるとテストはエラーで終了。
なぜかわからず$requestの中身を見てみると、渡したかった destination=>東京 がheadersにラインナップされていました。

urlにもパラメーターがついてない・・・

正しい書き方
こちらのサイトに記載の方法、routeヘルパの第二引数で渡すことで解決しました。
/**
* @test
* @covers \App\Controllers\Api\TwitterController::getWeather
*/
public function getWeather()
{
$data = ['destination' => '東京'];
$response = $this->get(route('getWeather', $data)); //ココを変更
$response->assertStatus(200);
}
これで無事アサート成功。
ちゃんとクエリパラメータにも入っていて

urlも期待通りになっていました。


