Test::...ookbook(3pm)
okay so welcome to Test::Roo::Cookbook(3pm) from the User Contributed Perl Documentation bestie, it's literally a cookbook of Test::Roo examples and it EATS. π
π NAME π
Test::Roo::Cookbook β Test::Roo examples. That's the whole vibe. π
π’ VERSION π’
version 1.004 β periodt. π
π¦ DESCRIPTION π¦
This file is where the usage ideas and examples for Test::Roo live. Not a reference manual, more like a mood board for your test suite. π
πΈ ORGANIZING TEST CLASSES AND ROLES πΈ
This is the "how do I even structure this" section and honestly it's so helpful.
β¨ Self-contained test file β¨
Sometimes you just want one test file, bestie. For simple tests where you want to use Moo attributes as fixtures that your test blocks get to share, a single file is lowkey perfect.
Here's an example that requires a corpus attribute, stashes the lines from that file in the lines attribute, and then makes it available to every single test block:
# examples/cookbook/single_file.t
use Test::Roo;
use MooX::Types::MooseLike::Base qw/ArrayRef/;
use Path::Tiny;
has corpus => (
is => 'ro',
isa => sub { -f shift },
required => 1,
);
has lines => (
is => 'lazy',
isa => ArrayRef,
);
sub _build_lines {
my ($self) = @_;
return [ map { lc } path( $self->corpus )->lines ];
}
test 'sorted' => sub {
my $self = shift;
is_deeply( $self->lines, [ sort @{$self->lines} ], "alphabetized");
};
test 'a to z' => sub {
my $self = shift;
my %letters = map { substr($_,0,1) => 1 } @{ $self->lines };
is_deeply( [sort keys %letters], ["a" .. "z"], "all letters found" );
};
run_me( { corpus => "/usr/share/dict/words" } );
# ... test other corpuses ...
done_testing;
Obsessed. β¨
π§ Standalone test class π§
Plot twist: you do not have to shove the test class inside the .t file. It's just a class. It can live anywhere. It has its own apartment. π
Same corpus-checking example as before, but now it's a class:
# examples/cookbook/lib/CorpusCheck.pm
package CorpusCheck;
use Test::Roo;
use MooX::Types::MooseLike::Base qw/ArrayRef/;
use Path::Tiny;
has corpus => (
is => 'ro',
isa => sub { -f shift },
required => 1,
);
has lines => (
is => 'lazy',
isa => ArrayRef,
);
sub _build_lines {
my ($self) = @_;
return [ map { lc } path( $self->corpus )->lines ];
}
test 'sorted' => sub {
my $self = shift;
is_deeply( $self->lines, [ sort @{$self->lines} ], "alphabetized");
};
test 'a to z' => sub {
my $self = shift;
my %letters = map { substr($_,0,1) => 1 } @{ $self->lines };
is_deeply( [sort keys %letters], ["a" .. "z"], "all letters found" );
};
1;
And the way that running it from a .t file doesn't even need Test::Roo?? Iconic:
# examples/cookbook/standalone.t
use strictures;
use Test::More;
use lib 'lib';
use CorpusCheck;
CorpusCheck->run_tests({ corpus => "/usr/share/dict/words" });
done_testing;
π Standalone Test Roles π
Okay THIS is the real power of Test::Roo β decomposing test behaviors into roles that you can reuse. Chef's kiss. π
Imagine we want to test a file-finder module like Path::Iterator::Rule. We could put tests for it into a role, then run the tests from a file that composes that role. For example, here's the test file:
# examples/cookbook/test-pir.pl
use Test::Roo;
use lib 'lib';
with 'IteratorTest';
run_me(
{
iterator_class => 'Path::Iterator::Rule',
result_type => '',
}
);
done_testing;
Then in the distribution for Path::Class::Rule, the same role could be tested with a test file like this:
# examples/cookbook/test-pcr.pl
use Test::Roo;
use lib 'lib';
with 'IteratorTest';
run_me(
{
iterator_class => 'Path::Class::Rule',
result_type => 'Path::Class::Entity',
},
);
done_testing;
So what's the common role they're consuming? π It sets up a test directory, creates files and runs tests:
# examples/cookbook/lib/IteratorTest.pm
package IteratorTest;
use Test::Roo::Role;
use MooX::Types::MooseLike::Base qw/:all/;
use Class::Load qw/load_class/;
use Path::Tiny;
has [qw/iterator_class result_type/] => (
is => 'ro',
isa => Str,
required => 1,
);
has test_files => (
is => 'ro',
isa => ArrayRef,
default => sub {
return [
qw(
aaaa
bbbb
cccc/dddd
eeee/ffff/gggg
)
];
},
);
has tempdir => (
is => 'lazy',
isa => InstanceOf ['Path::Tiny']
);
has rule_object => (
is => 'lazy',
isa => Object,
clearer => 1,
);
sub _build_description { return shift->iterator_class }
sub _build_tempdir {
my ($self) = @_;
my $dir = Path::Tiny->tempdir;
$dir->child($_)->touchpath for @{ $self->test_files };
return $dir;
}
sub _build_rule_object {
my ($self) = @_;
load_class( $self->iterator_class );
return $self->iterator_class->new;
}
sub test_result_type {
my ( $self, $file ) = @_;
if ( my $type = $self->result_type ) {
isa_ok( $file, $type, $file );
}
else {
is( ref($file), '', "$file is string" );
}
}
test 'find files' => sub {
my $self = shift;
$self->clear_rule_object; # make sure have a new one each time
$self->tempdir;
my $rule = $self->rule_object;
my @files = $rule->file->all( $self->tempdir, { relative => 1 } );
is_deeply( \@files, $self->test_files, "correct list of files" )
or diag explain \@files;
$self->test_result_type($_) for @files;
};
# ... more tests ...
1;
One role, two distributions, zero duplicated suffering. That's the dream. π¦
π CREATING AND MANAGING FIXTURES π
Fixtures! The little setup guys that your tests need before they can do their thing. Let's talk about them.
β Skipping all tests β
If you need to skip all the tests in the .t file β because some prerequisite isn't available, or some fixture just couldn't be built β use a BUILD method and call plan skip_all => $reason.
use Class::Load qw/try_load_class/;
has fixture => (
is => 'lazy',
);
sub _build_fixture {
# ... something that might die if unavailable ...
}
sub BUILD {
my ($self) = @_;
try_load_class('Class::Name')
or plan skip_all => "Class::Name required to run these tests";
eval { $self->fixture }
or plan skip_all => "Couldn't build fixture";
}
No half-broken test runs, no crying in the group chat. π
π Setting a test description π
You can override _build_description to build a test description out of your other attributes. For example, the IteratorTest package from earlier had these lines:
has [qw/iterator_class result_type/] => (
is => 'ro',
isa => Str,
required => 1,
);
sub _build_description { return shift->iterator_class }
So iterator_class is required, and then the description just gets set to it. Simple, clean, slay.
Or, if you're feeling extra, there could be a more verbose description:
sub _build_description {
my $name = shift->iterator_class;
return "Testing the $name class"
}
π« Requiring a builder π«
A test role can specify a lazy attribute and then require the consuming class to provide a builder for it. (Very "you bring the snacks, I'll bring the party" energy.)
In the test role:
has fixture => (
is => 'lazy',
);
requires '_build_fixture';
In the consuming class:
sub _build_fixture { ... }
π Clearing fixtures π
If a fixture has a clearer method, it can be easily reset during testing. And this works really well with lazy attributes, because they just get regenerated on demand. Fresh fixture, who dis.
has fixture => (
is => 'lazy',
clearer => 1,
);
test "some test" => sub {
my $self = shift;
$self->clear_fixture;
...
};
π₯ MODIFIERS FOR SETUP AND TEARDOWN π₯
The before-and-after of test life. π
π«Ά Setting up a fixture before testing π«Ά
When you need to do some extra work to set up a fixture, you can put a method modifier on the setup method. In some cases, this is more intuitive than doing all the work inside an attribute builder. Your call, bestie.
Here's an example that creates an SQLite table before any tests run, then cleans up afterwards:
# example/cookbook/sqlite.t
use Test::Roo;
use DBI;
use Path::Tiny;
has tempdir => (
is => 'ro',
clearer => 1,
default => sub { Path::Tiny->tempdir },
);
has dbfile => (
is => 'lazy',
default => sub { shift->tempdir->child('test.sqlite3') },
);
has dbh => ( is => 'lazy', );
sub _build_dbh {
my $self = shift;
DBI->connect(
"dbi:SQLite:dbname=" . $self->dbfile, { RaiseError => 1 }
);
}
before 'setup' => sub {
my $self = shift;
$self->dbh->do("CREATE TABLE f (f1, f2, f3)");
};
after 'teardown' => sub { shift->clear_tempdir };
test 'first' => sub {
my $self = shift;
my $dbh = $self->dbh;
my $sth = $dbh->prepare("INSERT INTO f(f1,f2,f3) VALUES (?,?,?)");
ok( $sth->execute( "one", "two", "three" ), "inserted data" );
my $got = $dbh->selectrow_arrayref("SELECT * FROM f");
is_deeply( $got, [qw/one two three/], "read data" );
};
run_me;
done_testing;
π Running tests during setup and teardown π
You can run any tests you like during setup or teardown. Not me realizing you can just... assert things in the hooks. The previous example could have written the setup and teardown hooks like this:
before 'setup' => sub {
my $self = shift;
ok( ! -f $self->dbfile, "test database file not created" );
ok( $self->dbh->do("CREATE TABLE f (f1, f2, f3)"), "created table");
ok( -f $self->dbfile, "test database file exists" );
};
after 'teardown' => sub {
my $self = shift;
my $dir = $self->tempdir;
$self->clear_tempdir;
ok( ! -f $dir, "tempdir cleaned up");
};
Main character energy from a before block, honestly. π
β¨ MODIFIERS ON TESTS β¨
π Global modifiers with "each_test" π
okay so bestie, modifying each_test triggers methods before or after every test block defined with the test function. Because this affects all tests, whether from the test class or composed from roles, it needs to be used thoughtfully β like, don't just slap it on and forget, okay? π
Here's an example that makes every test block run in its own separate temporary directory. obsessed with the efficiency, no cap.
# examples/cookbook/with_tempd.t
use Test::Roo;
use File::pushd qw/tempd/;
use Cwd qw/getcwd/;
has tempdir => (
is => 'lazy',
isa => sub { shift->isa('File::pushd') },
clearer => 1,
);
# tempd changes directory until the object is destroyed
# and the fixture caches the object until cleared
sub _build_tempdir { return tempd() }
# building attribute will change to temp directory
before each_test => sub { shift->tempdir };
# clearing attribute will change to original directory
after each_test => sub { shift->clear_tempdir };
# do stuff in a temp directory
test 'first test' => sub {
my $self = shift;
is( $self->tempdir, getcwd(), "cwd is " . $self->tempdir );
# ... more tests ...
};
# do stuff in a separate, fresh temp directory
test 'second test' => sub {
my $self = shift;
is( $self->tempdir, getcwd(), "cwd is " . $self->tempdir );
# ... more tests ...
};
run_me;
done_testing;
π¦ Individual test modifiers π¦
If you want method modifiers on one single test instead of all of them, put your Test::More tests in a method, add modifiers to that method, and use test to invoke it. It's giving main character energy but for one test only.
# examples/cookbook/hookable_test.t
use Test::Roo;
has counter => ( is => 'rw', default => sub { 0 } );
sub is_positive {
my $self = shift;
ok( $self->counter > 0, "counter is positive" );
}
before is_positive => sub { shift->counter( 1 ) };
test 'hookable' => sub { shift->is_positive };
run_me;
done_testing;
π Wrapping tests π
As a middle ground between global and individual modifiers, if you need to call some code repeatedly for some, but not all tests, you can create a custom test function. This might make sense for only a few tests, but could be helpful if there are many that need similar behavior, but you can't make it global by modifying each_test. lowkey genius, fr fr.
The following example clears the fixture before tests defined with the fresh_test function.
# examples/cookbook/wrapped.t
use strict;
use Test::Roo;
has fixture => (
is => 'rw',
lazy => 1,
builder => 1,
clearer => 1,
);
sub _build_fixture { "Hello World" }
sub fresh_test {
my ($name, $code) = @_;
test $name, sub {
my $self = shift;
$self->clear_fixture;
$code->($self);
};
}
fresh_test 'first' => sub {
my $self = shift;
is ( $self->fixture, 'Hello World', "fixture has default" );
$self->fixture("Goodbye World");
};
fresh_test 'second' => sub {
my $self = shift;
is ( $self->fixture, 'Hello World', "fixture has default" );
};
run_me;
done_testing;
π AUTHOR π
This absolute icon is David Golden <dagolden@cpan.org> β show some respect, bestie. π«Ά
π COPYRIGHT AND LICENSE π
This software is Copyright (c) 2013 by David Golden. periodt.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
And that's the whole tea, bestie. This page came from perl v5.34.0, dated 2022-06-28, and it's Test::...ookbook(3pm) β iconic, your honor π
β¨
π¦ where this page comes from
- debian bookworm: libtest-roo-perl 1.004-2 Β· Apache-2.0
- debian trixie: libtest-roo-perl 1.004-2 Β· Apache-2.0
- ubuntu noble: libtest-roo-perl 1.004-2 Β· Apache-2.0
- ubuntu resolute: libtest-roo-perl 1.004-2 Β· Apache-2.0
- ubuntu stonking: libtest-roo-perl 1.004-2 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms