ちーぶーうな

コードを書いたり写真を撮ったりします。

Mojolicious のテストがコケた時に CLI にエラーを出す

Mojolicious アプリのテストをやっていると、 500 エラーになるようなコケ方をしたときに、 CLI にエラーが出てこなくて原因を調べるのがちょっとめんどくさいですが、こんな風にテストを動かすといい感じになります。

Mojolicious 5.39 以前

ちょっと前の Mojolicious では、コントローラでコケた際には Mojolicious::Controller::render_exception が呼ばれるようになっていたので、そのメソッドに monkey patch する。

use common::sense;
use Mojolicious::Lite;
use Test::Mojo;
use Test::More;
use Test::Pretty;

is $Mojolicious::VERSION, '5.39';

get '/' => sub { die 'Hoge'; };

{
    no strict 'refs';
    no warnings 'redefine';

    *Mojolicious::Controller::render_exception = sub {
        my ($c, $e) = @_;
        print "\n\n", "*** Exception thrown:\n";
        warn $e;
        print "\n\n";
        $c->rendered(500);
        $c;
    };
};

my $t = Test::Mojo->new;

$t->get_ok('/')->status_is(200);

done_testing;

結果:

% carton exec -- perl -Ilib test.pl
✓    L7: is $Mojolicious::VERSION, '5.39';


*** Exception thrown:
Hoge at test.pl line 9.


✓  GET /
✖  200 OK
#   Failed test '200 OK'
#   at test.pl line 27.
#          got: '500'
#     expected: '200'

Mojolicious 5.40 以降

新しい方の Mojolicious では、 Mojolicious::Plugin::DefaultHelpers から追加される、 'reply.exception' というヘルパーが呼び出されるようになっていたので、テストでは上書きする。

use common::sense;
use Mojolicious::Lite;
use Test::Mojo;
use Test::More;
use Test::Pretty;

is $Mojolicious::VERSION, '5.72';

get '/' => sub { die 'Hoge'; };

my $t = Test::Mojo->new;

$t->app->helper(
    'reply.exception' => sub {
        my ($c, $e) = @_;
        print "\n\n", "*** Exception thrown:\n";
        warn $e;
        print "\n\n";
        $c->rendered(500);
        $c;
    }
);

$t->get_ok('/')->status_is(200);

done_testing;

結果:

% perl test.pl
✓    L7: is $Mojolicious::VERSION, '5.72';


*** Exception thrown:
Hoge at test.pl line 9.


✓  GET /
✖  200 OK
#   Failed test '200 OK'
#   at test.pl line 24.
#          got: '500'
#     expected: '200'

Term::ANSIColor なんかを使って、いい色にするとなおわかりやすいと思います。