Search code examples
perlmojolicious

How to use route name while testing mojolicious application?


I have read Test::Mojo but do not find how to use route name while application testing:

$t->get_ok( 'list_users' )->status_is( 302 )->location_is( 'auth_login' );

Where list_users and auth_login are:

$r->get( '/login' )->to( 'auth#login' )->name( 'auth_login' );
$r->get( '/users' )->to( 'user#index' )->name( 'list_users' );

I seems to me it will be very handy if *_ok will count given string same as redirect_to does. VOTEUP if this looks good for feature request to you too.

As work around this problem I try to use url_for without success:

$t->url_for( 'list_users' );
#Can't locate object method "url_for" via package "Test::Mojo"

How can I get route path by its name from test script?


Solution

  • I use Test::Mojo::Role as adviced by Sebastian Riedel:

    package Test::Mojo::Role::MyRole;
    
    use Role::Tiny;
    use Test::More;
    
    sub _build_ok {
        my( $self, $method, $url ) =  ( shift, shift, shift );
    
        if( my $route =  $t->app->routes->lookup( 'list_users' ) ) {
            $url =  $route->render;
        }
    
        local $Test::Builder::Level = $Test::Builder::Level + 1;
        return $self->_request_ok( $self->ua->build_tx( $method, $url, @_ ), $url );
    }
    
    
    
    sub location_is {
      my( $t, $url, $desc ) =  @_;
    
      if( my $route =  $t->app->routes->lookup( 'list_users' ) ) {
          $url =  $route->render;
      }
      $desc //=  "Location: $url";
    
      local $Test::Builder::Level =  $Test::Builder::Level + 1;
      return $t->success( is($t->tx->res->headers->location, $url, $desc) );
    }
    
    
    #myapp.t
    
    use Test::Mojo::WithRoles 'MyRole';
    our $t =  Test::Mojo::WithRoles->new( 'MyApp' );
    
    $t->get_ok( 'list_users' )->status_is( 302 )->location_is( 'auth_login' );
    

    UPD

    That is better to do reverse: try to get route name from location and compare it to expected result