Search code examples
perltestingdancer

How to run a Perl Dancer Test


Reading through the Dancer::Test documentation made it seem straightforward to do a test, but I'm missing something. If I have the following Dancer application (WebApp.pm):

package WebApp;
use Dancer;

# declare routes/actions
get '/' => sub {
    "Hello World";
};

dance;

and then the following testing file 001_base.t:

use strict;
use warnings;
use Test::More tests => 1;

use WebApp;
use Dancer::Test;

response_status_is [GET => '/'], 200, "GET / is found";

Then when I run the test: perl 001_base.t, the output is that the dancer script starts up:

Dancer 1.3132 server 7679 listening on http://0.0.0.0:3000
== Entering the development dance floor ...

But then waits. (This is the same as if I just run the code in WebApp.pm). What am I missing here? I guess I'm not running the test correctly.


Solution

  • You should remove dancer() from the WebApp.pm. Here is the correct content:

    package WebApp;
    use Dancer;
    
    # declare routes/actions
    get '/' => sub {
        "Hello World";
    };
    
    1;
    

    Then you test will pass.

    The common way to create dancer apps is to declare all the routes in one or more .pm files and to have a file usually called app.psgi with the content:

    #!/usr/bin/env perl
    use Dancer;
    use WebApp;
    dance;
    

    Then to start your web application you should run perl -Ilib app.psgi.