Search code examples
perlunit-testingmojolicious

How to test for a redirect in Mojolicious?


I want to test a page with a form which, when submitted, will redirect to the resulting page for the submitted item.

My Mojolicious controller contains:

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");
}

The test script for this controller contains:

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);

My issue is that it stops with the 302 status. How do I proceed with the redirect so I can verify the resulting item page?


Solution

  • Set the matching setting from Mojo::UserAgent:

    $t->ua->max_redirects(10)
    

    Also, you don't need to build the form post manually:

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


    Reference: