如何在Mojolicious中测试重定向?

时间:2012-09-08 06:01:56

标签: perl unit-testing mojolicious

我想测试一个表单,该表单在提交时会重定向到提交项目的结果页面。

我的Mojolicious控制器包含:

sub submit_new {
    my $self = shift;

    my $new = $self->db->resultset('Item')->new( {
        title       => $self->param('title'),
        description => $self->param('description'),
    } );
    $new->insert;

    # show the newly submitted item
    my $id = $new->id;
    $self->redirect_to("/items/$id");
}

此控制器的测试脚本包含:

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

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

my $tx = $t->ua->build_form_tx('/items/new/submit' => $data);
$tx->req->method('POST');
$t->tx( $t->ua->start($tx) )
  ->status_is(302);

我的问题是它以302状态停止。如何继续重定向,以便我可以验证生成的项目页面?

2 个答案:

答案 0 :(得分:7)

从Mojo :: UserAgent设置匹配设置:

$t->ua->max_redirects(10)

此外,您无需手动构建表单帖子:

$t->post_form_ok('/items/new/submit' => $data)->status_is(...);


参考:

答案 1 :(得分:1)

您还可以(也许应该)测试成功登录已重定向到的登录页面的内容:

my $tm = '' ; # the test message for each test
my $t = Test::Mojo->new('Qto');
$t->ua->max_redirects(10);
my $app = 'foobar';
my $url = '/' . $db_name . '/login' ;

 $tm = "a successfull result redirects to the home page";
 my $tx = $t->ua->post( $url => 'form'  => {'email' =>'test.user@gmail.com', 'pass' => 'secret'});
 ok ( $tx->result->dom->all_text =~ "$app home" , $tm );

the docs for how-to get the content with mojo dom

the mojo dom selector syntax doc link

an example testing script with login testing