LoginSignup
18
17

More than 5 years have passed since last update.

Laravelのユニットテストとデバッグ&ログの出し方

Last updated at Posted at 2016-01-03

LaravelにはXcodeのような行ごとのステップ実行できるデバッガーはない。
なので、実行中にHTML上に表示させるかファイルへのログ出力を行うしか方法がない。

1.HTML上に出す方法
ベタにvar_dumpかprint_rを使う(PHPのお約束)

2.ログファイルに書き出す方法
Logファサードを使ってファイルに吐き出す。
【注意点】
 ・ファサードなのでuse Logが必要
 ・config/app.phpファイルのAPP_DEBUG属性(もしくは.envファイルの同箇所)をtrueにする

ということで以下使用例。ここに詳細は出ています。

use App\Restaurant;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Log;

class AreaController extends Controller
{
//
public function index()
{
    $restaurant = Restaurant::all();

Log::info('Showing user profile for user: '.$restaurant);
    return view('area', ['restaurants' => $restaurant]);
}

public function show($id)
{
    $restaurant = Restaurant::where('areaid', $id)->first();

var_dump($id);
print_r($restaurant);

    return view('areashow', ['restaurant' => $restaurant]);
}

さて、ユニットテストについてであるが、とてもシンプル。
作成したプロジェクト配下のtestsディレクトリにあるExampleTest.phpを修正してもいいし、以下のコマンドで新規作成してもよし。

php artisan make:test UserTest

指定したアドレス(ドメイン直打ちとかの場合は/)で特定の文字が含まれて欲しければ以下の様な書き方となる。

public function testBasicExample() 
{
    $this->visit('/')
         ->see('Laravel 5');
    $this->visit('/area')
         ->see('test 8');
    $this->visit('/area/25')
         ->see('Laravel 5');
}

これを書いたらあとは

phpunit

とプロジェクトのデフォルトディレクトリからコマンドラインで入力すればテストが簡単に実行できる。

全部成功の例

PHPUnit 4.8.21 by Sebastian Bergmann and contributors.

.

Time: 4.1 seconds, Memory: 14.50Mb

OK (1 test, 4 assertions)

一部失敗の例:
 HTML吐き出しをして、エラーになった箇所のテストの行が出る

Time: 4.25 seconds, Memory: 14.50Mb

There was 1 failure:

1) ExampleTest::testBasicExample
Failed asserting that '<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<body>
    <h1>Hello, Area id = 8</h1>
<p>test 黄金屋</p>
</body>
</html>
' matches PCRE pattern "/Laravel 5/i".

/home/vagrant/Code/petittdt/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:188
/home/vagrant/Code/petittdt/tests/ExampleTest.php:21

FAILURES!
Tests: 1, Assertions: 6, Failures: 1.

ここに詳細は出ています。

18
17
1

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
18
17