WWW::Mechanize::TreeBuilder
Last week at YAPC::EU I saw a few interesting talks, including Stevan's Moose introduction. I found this talk really helpful, maybe in part because I had read through Moose's documentation and cookbook examples once a month or so ago.
So I wanted to learn Moose a bit better, and I'm a firm believer of learning new technologies by actually writing something using them, so I needed a project - not to complex, but also not trivial. And I had just the thing - something I made a start on in June, but sadly only ever existed on my laptop that got stolen. I present the following code snippet for consideration taken from a test suite at work:
my $mech = WWW::Mechanize->new;
ok( $mech->get("$base/index") );
ok( $mech->content =~ m{<div id="header">Welcome To My Site</div>} );
What's wrong with it? Well for a start, it should be using Test::WWW::Mechanize which fixes a few problems. But its still parsing XHTML (you do write XHTML web sites don't you.) using a regexp, which is always a bad idea. What happens if you change the ID of the element, or add a class to it? It'll stop working and your tests will break. My solution? WWW::Mechanize::TreeBuilder:
my $mech = Test::WWW::Mechanize->new;
WWW::Mechanize::TreeBuilder->meta->apply($mech);
$mech->get_ok("$base/index");
is( $mech->look_down(_tag => 'div', id => 'header')->as_trimmed_text, 'Welcome To My Site');
Much better.
Comments on WWW::Mechanize::TreeBuilder | no comments | Post a comment