[Catalyst] Unit tests for controllers based on Catalyst::Controller::REST?

Bill Moseley moseley at hank.org
Wed Dec 29 15:38:41 GMT 2010


On Tue, Dec 28, 2010 at 8:32 PM, James Russo <jr at halo3.net> wrote:

> # create
> ok($response =3D request(
>                        POST('/appointment','content-type' =3D>
> 'application/json', 'content' =3D> to_json($foo)
>                        ),
>                        "create new appointment"));
>
> Just wanted to put it out there in the archives for the next person.
>

Again, my suggestion is you put that into a test class  -- you probably
don't want to type that dozens (if not hundreds) of times.  And if your
application grows you will likely want some kind of custom test framework
that all your test files use.  And If you work with other developers it's
helpful to have a simple test framework that's easy for everyone to use and
understand.

I use a generic test class that provides methods for making different types
of request and decoding responses, provides a $schema object (as you need to
modify data during a test), building and tearing down test data, and
provides access to the app configuration.   I can enable a debug option to
dump full request and response and the class allows single-stepping through
the tests.  And with your REST-like methods you probably want to know more
than than $response->is_success (which is what post_ok() checks).  I then
sub-class that for each application so I can add specific helper methods
unique to that app.

So, tests end up something like:

my $test =3D Test::MyApp->new( debug_response =3D> 0, dbic_trace =3D> 0 );

my $user =3D $test->create_and_login_test_user;

$test->json_request( 201, POST =3D> $path, \%data );  # OK if status =3D=3D=
 201,
and print message about request.

my $response =3D $test->request( 200, GET =3D> $path );  # $response is
HTTP::Response sub-class.

my $data =3D $response->decoded_content;
$data->{foo} =3D 'bar';  # modify response data before PUT

$test->json_request( 204, PUT =3D> $path, $data );


The *request methods allow passing an HTTP::Request object, too, so it's
easy to customize a request for the rare times I need a custom header.



-- =

Bill Moseley
moseley at hank.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.scsys.co.uk/pipermail/catalyst/attachments/20101229/a114e=
3d4/attachment.htm


More information about the Catalyst mailing list