【问题标题】:How to test for a redirect in Mojolicious?如何在 Mojolicious 中测试重定向?
【发布时间】:2012-09-01 22:45:28
【问题描述】:

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

我的 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 状态停止。如何进行重定向,以便验证生成的项目页面?

【问题讨论】:

    标签: perl unit-testing mojolicious


    【解决方案1】:

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

    $t->ua->max_redirects(10)
    

    另外,您不需要手动构建表单帖子:

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


    参考:

    【讨论】:

    • post_form_ok 似乎不再存在 - 或者只是语法改变了?
    • 确实; post_form 也曾存在于 Mojo::UserAgent 中。它们已被合并到 post 中,因此新的用法是: $t->post_ok($url => form => $data);
    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      相关资源
      最近更新 更多