How to test for a redirect in Mojolicious?
Asked Answered
B

2

6

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?

Billy answered 8/9, 2012 at 6:1 Comment(0)
I
9

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:

Inadmissible answered 8/9, 2012 at 6:18 Comment(2)
post_form_ok seems not to exist any more - or has just the syntax changed?Percussion
Indeed; post_form used to exist in Mojo::UserAgent as well. They've been merged into post, so the new usage would be: $t->post_ok($url => form => $data);Inadmissible
S
1

You could also (and probably should) test the content of the landing page to which the successful login has redirected :

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' =>'[email protected]', '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

Sherr answered 9/7, 2019 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.