3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Test::Mojoでビルドされたアプリにブラウザでアクセスする

Last updated at Posted at 2014-05-27

概要

テストがなんか失敗してよくわからない場合、
ブラウザで操作して確認してみたい時がある。

フィクスチャ設定などもそのまま残るので、できると便利。

一時的なサーバを立ち上げる

Net::EmptyPort + Mojo::Server::Daemon で、
一時的なサーバを立ち上げる。

Net::EmptyPortは、Test::TCPに同封されているモジュールなので、
入っていない場合はTest::TCPをインストールする。

以下のような関数を用意する。

t/Util.pm
package t::Util;
use strict;
use warnings;
use utf8;
use Net::EmptyPort qw(empty_port);
use Mojo::Server::Daemon;

sub run_server {
    my ($app) = @_;
    my $port = empty_port();
    warn "Accepting connections at http://*:$port/\n";
    my $daemon = Mojo::Server::Daemon->new(listen => ['http://*:'.$port]);
    $daemon->app($app);
    $daemon->run;
}

1;

あとはテストでデバッグしたいタイミングで、
以下のように記述する。

t/base.t
use strict;
use warnings;

use Test::More;
use Test::Mojo;

use t::Util;

my $t = Test::Mojo->new('MyApp');

# ここでサーバが立ち上がり、ブロックされる
t::Util::run_server($t->app);

$t->get_ok('/')->status_is(200)->content_like(qr/Mojolicious/i);

done_testing;

テストを実行するとコメントの部分でブロックされ、
出力でListenしているURLが表示される。

$ prove -l t/base.t
t/basic.t .. Accepting connections at http://*:50277/

この場合、「 http://localhost:50277/ 」をブラウザに入力すると、
アプリの画面が表示される。

「Ctrl+C」で終了させる。

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?