前提
Laravelのテスト用メソッドについてメモしていきます。
本題
ステータスのチェック
$this->get('/')->assertStatus(200);
ステータスOKのチェック
$this->get('/hello')->assertOk();
POSTのチェック
$this->post('/hello')->assertOk();
パラメータを指定する
$this->get('/hello/1')->assertOk();
存在しないページのチェック
$this->get('/hoge')->assertStatus(404);
※用意していないアドレスを指定し、ステータスコードが404かどうかをチェック。
不用意に「存在しないはずのページにアクセスできてしまう」といったことを確認できる。
コンテンツに含まれるテキスト
$this->get('/hello')->assertSeeText('Index');
レスポンスに含まれるテキスト
$this->get('/hello')->assertSee('<h1>');
用意したテキストが順に登場する
$this->get('/hello')->assertSeeInOrder(['<html','<head','<body','<h1>']);
Ajaxへのアクセス
$this->get('/hello/json/1')->assertSeeText('YAMADA-TARO');
Ajaxの内容チェック
$this->get('/hello/json/2')->assertExactJson(
['id'=2, 'name'=>'HANAKO',
'mail'=>'hanako@flower','age'=>'19']);
各テスト後のデータベースリセット
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
class ExampleTest extends TestCase
{
use RefreshDatabase; #この記述でリセット可能
/**
* 基本的な機能テストの例
*
* @return void
*/
public function testBasicExample()
{
$response = $this->get('/');
// …
}
}