Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
stevenl Avatar asked Sep 08 '12 06:09

stevenl


2 Answers

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:

  • http://mojolicio.us/perldoc/Test/Mojo#ua
  • http://mojolicio.us/perldoc/Mojo/UserAgent#max_redirects
  • http://mojolicio.us/perldoc/Test/Mojo#post_form_ok
like image 158
tempire Avatar answered Oct 14 '22 23:10

tempire


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

like image 33
Yordan Georgiev Avatar answered Oct 14 '22 21:10

Yordan Georgiev