Test::WWW::Mechanize tricks

perrin on 2006-04-26T20:10:01

Sometimes I want to test if my application sent the right redirect, but I don't want to follow it. It might be to a page that isn't accessible from my dev system, or is hosted by someone else and I don't want to hit it every time I run the test suite.

To do this with Test::WWW::Mechanize, I use this code:

my $mech = Test::WWW::Mechanize->new(autocheck => 0);
$mech->requests_redirectable([]);    # don't follow redirects
$mech->get($uri);
is($mech->status, 302);
$mech->content_contains($url_to_redirect_to, 'sent to correct URL');


Another thing I want to check is if the request set a cookie. A simple way to do that:

my $resp = $mech->get($uri);
ok($resp->header('Set-Cookie'), 'has cookie header');
like($mech->cookie_jar->as_string(), qr/$COOKIE_NAME/,
     'cookie was accepted');


Since the LWP cookie handling does the same checks that browsers do for domain and path, this can help catch problems with your cookie headers.


HTTP Redirect Headers

Dom2 on 2006-04-26T23:55:00

Just a minor point -- aren't you better off testing the contents of the Location header rather than the body in that first example?

-Dom

Re:HTTP Redirect Headers

perrin on 2006-04-26T23:57:37

Probably. I always put the URL in both places.

Re:HTTP Redirect Headers

Dom2 on 2006-04-27T07:53:28

It's just that I have managed to produce redirects with no body before. I've been a bit paranoid since then.

-Dom

thanks

markjugg on 2007-07-09T20:58:08

This little snippet example for testing for the presence of a cookie being set was just what I needed today. Thanks!