tokuhirom's Blog

Module::Spy - Spy for Perl5

I released the new great Module::Spy. Repository is now on github.com/tokuhirom/Module-Spy.git.

I saw jasmine at few days ago. jasmine is very popular BDD testing framework for JavaScript. jasmine has the great interface for spy. A spy can stub any function and tracks calls to it and all arguments.

I'm using the local feature in the past days. Because it's good enough for me.

For example, following script works well.

use LWP::UserAgent;

my $called = 0;
no warnings 'redefine';
local *LWP::UserAgent::request = sub {
    $called++;
    HTTP::Response->new(200);
};
my $ua = LWP::UserAgent->new;
my $res = $ua->get('http://mixi.jp');
ok $called;

It works well... But the code is bit complicated.

When if you are using Module::Spy, you can write the code as following:

use LWP::UserAgent;
use Module::Spy;

my $spy = spy_on('LWP::UserAgent', 'request')->and_returns(
    HTTP::Response->new(200);
);
my $ua = LWP::UserAgent->new;
my $res = $ua->get('http://mixi.jp');
ok $spy->called_any;

The code is really readable!

And also, you can send spy for objects. It uses the Singleton class pattern.

my $ua = LWP::UserAgent->new;
my $spy = spy_on($ua, 'request')->and_returns(
    HTTP::Response->new(200);
);
my $res = $ua->get('http://mixi.jp');
ok $spy->called_any;

And so, Module::Spy restores the methods after $spy was gone!

Enjoy!