[Catalyst] Testing Catalyst::Controller::REST based controllers

Ash Berlin ash_cpan at firemirror.com
Tue Feb 26 20:23:48 GMT 2008


On 26 Feb 2008, at 20:20, Damon Snyder wrote:

> Hi Everyone,
> I'm developing a Catalyst::Controller::REST based controller in an  
> app that I'm working on. I've created the _GET and _POST methods and  
> now I'm trying to test them. They work fine if I test them using  
> curl from the command line or LWP::UserAgent, but now I'm trying to  
> add tests for them using Test::WWW::Mechanize::Catalyst.
>
> I'm having a hard time getting Test::WWW::Mechanize::Catalyst to  
> interact my REST controller. I can build the request fine with  
> HTTP::Request and LWP::UserAgent, but I can't seem to get it to work  
> with Test::WWW::Mechanize::Catalyst. Does anyone have any example  
> code where they were able to get the GET, POST, and PUT to test  
> successfully using Test::WWW::Mechanize::Catalyst?
>
> Here is the basic construction of the POST with LWP::UserAgent and  
> Test::More:
>
> my $ua = new LWP::UserAgent;
> $ua->default_header( 'X-Username' => 'xxxx', 'X-Password' =>  
> 'xxxxx' );
>
> #my $req = new HTTP::Request POST => "http://localhost/rest/ 
> something";
> $req->content_type('text/x-json');
> $req->content(to_json(( { name => "bla", foo => "haaa" } ));
>
> my $res = $ua->request($req);
>
> ok($res, "Request was successful");
> ok($res->headers->{status} == 201);
>
> my $something = from_json($res->content);
> ok($something->{foo} eq 'haaa');
>
> I could continue with LWP::UserAgent, but it seems easier and more  
> maintainable to use the catalyst mechanize route if possible  
> (testing against other servers, don't need local server running etc).
>
> Thanks,
> Damon
>

     sub make_json_request {
         my ($self, $uri, $data) = @_;

         my $req = POST( $uri,
             Content_Type => 'text/json',
             Content => $self->to_json($data)
         );

         my $res = $self->mech->request($req);

         return unless $res->code == 200;

         die "JSON request returned 200 but not correct Content-Type  
(@{[$res->content_type]})"
             unless $res->header('Content-Type') eq 'text/javascript';

         return $self->from_json($res->content);
     }


$self->mech returns a Test:WWW::Mechanize::Catalyst instance.

POST method comes from

use HTTP::Request::Common;

Not that disimilar from what you had, just notice that $mech->request  
will take a HTTP::Request object as well as just a URI.

Ash



More information about the Catalyst mailing list