Test::Spec(3pm) | User Contributed Perl Documentation | Test::Spec(3pm) |
Test::Spec - Write tests in a declarative specification style
use Test::Spec; # automatically turns on strict and warnings describe "A date" => sub { my $date; describe "in a leap year" => sub { before each => sub { $date = DateTime->new(year => 2000, month => 2, day => 28); }; it "should know that it is in a leap year" => sub { ok($date->is_leap_year); }; it "should recognize Feb. 29" => sub { is($date->add(days => 1)->day, 29); }; }; describe "not in a leap year" => sub { before each => sub { $date = DateTime->new(year => 2001, month => 2, day => 28); }; it "should know that it is NOT in a leap year" => sub { ok(!$date->is_leap_year); }; it "should NOT recognize Feb. 29" => sub { is($date->add(days => 1)->day, 1); }; }; }; runtests unless caller; # Generates the following output: # ok 1 - A date in a leap year should know that it is in a leap year # ok 2 - A date in a leap year should recognize Feb. 29 # ok 3 - A date not in a leap year should know that it is NOT in a leap year # ok 4 - A date not in a leap year should NOT recognize Feb. 29 # 1..4
This is a declarative specification-style testing system for behavior-driven development (BDD) in Perl. The tests (a.k.a. examples) are named with strings instead of subroutine names, so your fingers will suffer less fatigue from underscore-itis, with the side benefit that the test reports are more legible.
This module is inspired by and borrows heavily from RSpec <http://rspec.info/documentation>, a BDD tool for the Ruby programming language.
When given no list (i.e. "use Test::Spec;"), this class will export:
These are the functions you will use to define behaviors and run your specs: "describe", "it", "they", "before", "after", "runtests", "share", "shared_examples_for", "it_should_behave_like", and "spec_helper".
This includes "ok", "is" and friends. You'll use these to assert correct behavior.
More assertions including "cmp_deeply".
The "trap()" function, which let you test behaviors that call "exit()" and other hard things like that. "A block eval on steroids."
If you specify an import list, only functions directly from "Test::Spec" (those documented below) are available.
If called as a function (i.e. not a method call with "->"), "runtests" will autodetect the package from which it is called and run that package's examples. A useful idiom is:
runtests unless caller;
which will run the examples when the file is loaded as a script (for example, by running it from the command line), but not when it is loaded as a module (with "require" or "use").
describe "A User object" => sub { my $user; before sub { $user = User->new; }; describe "from a web form" => sub { before sub { $user->init_from_tree({ username => "bbill", ... }); }; it "should read its attributes from the form"; describe "when saving" => sub { it "should require a unique username"; it "should require a password"; }; }; };
The setup work done in each "before" block cascades from one level to the next, so you don't have to make a call to some initialization function manually in each test. It's done automatically based on context.
describe "An unladen swallow" => sub { it "has an airspeed of 11 meters per second" => sub { is($swallow->airspeed, "11m/s"); }; };
The output generated is:
ok 1 - An unladen swallow has an airspeed of 11 meters per second
Contrast this to the following test case to generate the same output:
sub unladen_swallow_airspeed : Test { is($swallow->airspeed, "11m/s", "An unladen swallow has an airspeed of 11 meters per second"); }
"describe" blocks execute in the order in which they are defined. Multiple "describe" blocks with the same name are allowed. They do not replace each other, rather subsequent "describe"s extend the existing one of the same name.
describe "A captive of Buffalo Bill" => sub { it "puts the lotion on its skin" => sub { ... }; it "puts the lotion in the basket"; # TODO };
If a code reference is not passed, the specification is assumed to be unimplemented and will be reported as "TODO (unimplemented)" in the test results (see "todo_skip" in Test::Builder. TODO tests report as skipped, not failed.
describe "Captives of Buffalo Bill" => sub { they "put the lotion on their skin" => sub { ... }; they "put the lotion in the basket"; # TODO };
The default is "each", due to this logic presented in RSpec's documentation:
"It is very tempting to use before(:all) and after(:all) for situations in which it is not appropriate. before(:all) shares some (not all) state across multiple examples. This means that the examples become bound together, which is an absolute no-no in testing. You should really only ever use before(:all) to set up things that are global collaborators but not the things that you are describing in the examples.
The most common cases of abuse are database access and/or fixture setup. Every example that accesses the database should start with a clean slate, otherwise the examples become brittle and start to lose their value with false negatives and, worse, false positives."
(<http://rspec.info/documentation/before_and_after.html>)
There is no restriction on having multiple before blocks. They will run in sequence within their respective "each" or "all" groups. "before "all"" blocks run before "before "each"" blocks.
"after "all"" blocks run after "after "each"" blocks.
our $var = 0; describe "Something" => sub { around { local $var = 1; yield; }; it "should have localized var" => sub { is $var, 1; }; };
This CODE will run around each example.
Example group names are global, but example groups can be defined at any level (i.e. they can be defined in the global context, or inside a "describe" block).
my $browser; shared_examples_for "all browsers" => sub { it "should open a URL" => sub { ok($browser->open("http://www.google.com/")) }; ... }; describe "Firefox" => sub { before all => sub { $browser = Firefox->new }; it_should_behave_like "all browsers"; it "should have firefox features"; }; describe "Safari" => sub { before all => sub { $browser = Safari->new }; it_should_behave_like "all browsers"; it "should have safari features"; };
Every hash that is "share"d refers to the same data. Sharing a hash will make its existing contents inaccessible, because afterwards it contains the same data that all other shared hashes contain. The result is that you get a hash with global semantics but with lexical scope (assuming %HASH is a lexical variable).
There are a few benefits of using "share" over using a "regular" global hash. First, you don't have to decide what package the hash will belong to, which is annoying when you have specs in several packages referencing the same shared examples. You also don't have to clutter your examples with colons for fully-qualified names. For example, at my company our specs go in the "ICA::TestCase" hierarchy, and "$ICA::TestCase::Some::Package::variable" is exhausting to both the eyes and the hands. Lastly, using "share" allows "Test::Spec" to provide this functionality without deciding on the variable name for you (and thereby potentially clobbering one of your variables).
share %vars; # %vars now refers to the global share share my %vars; # declare and share %vars in one step
# in foo/spec.t spec_helper "helper.pl"; # loads foo/helper.pl spec_helper "helpers/helper.pl"; # loads foo/helpers/helper.pl spec_helper "/path/to/helper.pl"; # loads /path/to/helper.pl
This feature comes straight out of RSpec, as does this documentation:
You can create shared example groups and include those groups into other groups.
Suppose you have some behavior that applies to all editions of your product, both large and small.
First, factor out the "shared" behavior:
shared_examples_for "all editions" => sub { it "should behave like all editions" => sub { ... }; };
then when you need to define the behavior for the Large and Small editions, reference the shared behavior using the "it_should_behave_like()" function.
describe "SmallEdition" => sub { it_should_behave_like "all editions"; }; describe "LargeEdition" => sub { it_should_behave_like "all editions"; it "should also behave like a large edition" => sub { ... }; };
"it_should_behave_like" will search for an example group by its description string, in this case, "all editions".
Shared example groups may be included in other shared groups:
shared_examples_for "All Employees" => sub { it "should be payable" => sub { ... }; }; shared_examples_for "All Managers" => sub { it_should_behave_like "All Employees"; it "should be bonusable" => sub { ... }; }; describe Officer => sub { it_should_behave_like "All Managers"; it "should be optionable"; }; # generates: ok 1 - Officer should be optionable ok 2 - Officer should be bonusable ok 3 - Officer should be payable
Refactoring into files
If you want to factor specs into separate files, variable scopes can be tricky. This is especially true if you follow the recommended pattern and give each spec its own package name. "Test::Spec" offers a couple of functions that ease this process considerably: share and spec_helper.
Consider the browsers example from "shared_examples_for". A real browser specification would be large, so putting the specs for all browsers in the same file would be a bad idea. So let's say we create "all_browsers.pl" for the shared examples, and give Safari and Firefox "safari.t" and "firefox.t", respectively.
The problem then becomes: how does the code in "all_browsers.pl" access the $browser variable? In the example code, $browser is a lexical variable that is in scope for all the examples. But once those examples are split into multiple files, you would have to use either package global variables or worse, come up with some other hack. This is where "share" and "spec_helper" come in.
# safari.t package Testcase::Safari; use Test::Spec; spec_helper 'all_browsers.pl'; describe "Safari" => sub { share my %vars; before all => sub { $vars{browser} = Safari->new }; it_should_behave_like "all browsers"; it "should have safari features"; }; # firefox.t package Testcase::Firefox; use Test::Spec; spec_helper 'all_browsers.pl'; describe "Firefox" => sub { share my %vars; before all => sub { $vars{browser} = Firefox->new }; it_should_behave_like "all browsers"; it "should have firefox features"; }; # in all_browsers.pl shared_examples_for "all browsers" => sub { # doesn't have to be the same name! share my %t; it "should open a URL" => sub { ok $t{browser}->open("http://www.google.com/"); }; ... };
This example, shamelessly adapted from the RSpec website, gives an overview of the order in which examples run, with particular attention to "before" and "after".
describe Thing => sub { before all => sub { # This is run once and only once, before all of the examples # and before any before("each") blocks. }; before each => sub { # This is run before each example. }; before sub { # "each" is the default, so this is the same as before("each") }; it "should do stuff" => sub { ... }; it "should do more stuff" => sub { ... }; after each => sub { # this is run after each example }; after sub { # "each" is the default, so this is the same as after("each") }; after all => sub { # this is run once and only once after all of the examples # and after any after("each") blocks }; };
RSpec <http://rspec.info>, Test::More, Test::Deep, Test::Trap, Test::Builder.
The mocking and stubbing tools are in Test::Spec::Mocks.
Philip Garrett <philip.garrett@icainformatics.com>
The source code for Test::Spec lives on github <https://github.com/kingpong/perl-Test-Spec>
If you want to contribute a patch, fork my repository, make your change, and send me a pull request.
If you have found a defect or have a feature request please report an issue at https://github.com/kingpong/perl-Test-Spec/issues. For help using the module, standard Perl support channels like Stack Overflow <http://stackoverflow.com/> and comp.lang.perl.misc <http://groups.google.com/group/comp.lang.perl.misc> are probably your best bet.
Copyright (c) 2010-2011 by Informatics Corporation of America.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2017-12-26 | perl v5.26.1 |