Test::Spec(3) Write tests in a declarative specification style

SYNOPSIS


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

DESCRIPTION

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.

EXPORTS

When given no list (i.e. "use Test::Spec;"), this class will export:
  • Spec definition functions

    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".

  • The stub/mock functions in Test::Spec::Mocks.
  • Everything that Test::More normally exports

    This includes "ok", "is" and friends. You'll use these to assert correct behavior.

  • Everything that Test::Deep normally exports

    More assertions including "cmp_deeply".

  • Everything that "Test::Trap" normally exports

    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.

FUNCTIONS

runtests
runtests(@patterns)
Runs all the examples whose descriptions match one of the (non case-sensitive) regular expressions in @patterns. If @patterns is not provided, runs all examples. The environment variable ``SPEC'' will be used as a default pattern if present.

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 DESCRIPTION => CODE
describe CODE
Defines a specification context under which examples and more descriptions can be defined. All examples must come inside a "describe" block.
"describe" blocks can be nested to DRY up your specs.
For large specifications, "describe" blocks can save you a lot of duplication:

  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.

Using describe blocks improves legibility without requiring more typing.
The name of the context will be included by default in the success/failure report generated by Test::Builder-based testing methods (e.g. Test::More's ok() function). For an example like this:

  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.

context
An alias for "describe()".
xdescribe
Specification contexts may be disabled by calling "xdescribe" instead of "describe()". All examples inside an "xdescribe" are reported as ``# TODO (disabled)'', which prevents Test::Harness/prove from counting them as failures.
xcontext
An alias for "xdescribe()".
it SPECIFICATION => CODE
it CODE
it TODO_SPECIFICATION
Defines an example to be tested. Despite its awkward name, "it" allows a natural (in my opinion) way to describe expected behavior:

  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.

they SPECIFICATION => CODE
they CODE
they TODO_SPECIFICATION
An alias for ``it''. This is useful for describing behavior for groups of items, so the verb agrees with the noun:

  describe "Captives of Buffalo Bill" => sub {
    they "put the lotion on their skin" => sub {
      ...
    };
    they "put the lotion in the basket"; # TODO
  };
xit/xthey
Examples may be disabled by calling xit()/xthey() instead of it()/they(). These examples are reported as ``# TODO (disabled)'', which prevents Test::Harness/prove from counting them as failures.
before each => CODE
before all => CODE
before CODE
Defines code to be run before tests in the current describe block are run. If ``each'' is specified, CODE will be re-executed for every test in the context. If ``all'' is specified, CODE will only be executed before the first test.

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 each => CODE
after all => CODE
after CODE
Like "before", but backwards. Runs CODE after each or all tests, respectively. The default is ``each''.

"after "all"" blocks run after "after "each"" blocks.

shared_examples_for DESCRIPTION => CODE
Defines a group of examples that can later be included in "describe" blocks or other "shared_examples_for" blocks. See ``Shared example groups''.

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";
  };
it_should_behave_like DESCRIPTION
Asserts that the thing currently being tested passes all the tests in the example group identified by DESCRIPTION (having previously been defined with a "shared_examples_for" block). In essence, this is like copying all the tests from the named "shared_examples_for" block into the current context. See ``Shared example groups'' and shared_examples_for.
share %HASH
Registers %HASH for sharing data between tests and example groups. This lets you share variables with code in different lexical scopes without resorting to using package (i.e. global) variables or jumping through other hoops to circumvent scope problems.

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
spec_helper FILESPEC
Loads the Perl source in "FILESPEC" into the current spec's package. If "FILESPEC" is relative (no leading slash), it is treated as relative to the spec file (i.e. not the currently running script). This lets you keep helper scripts near the specs they are used by without exercising your File::Spec skills in your specs.

  # 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

Shared example groups

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/");
    };
    ...
  };

Order of execution

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
    };
  };

AUTHOR

Philip Garrett <[email protected]>

CONTRIBUTING

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.

SUPPORT

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 & LICENSE

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.