File Coverage

blib/lib/Test/Spec.pm
Criterion Covered Total %
statement 202 223 90.5
branch 42 62 67.7
condition 20 40 50.0
subroutine 44 47 93.6
pod 14 21 66.6
total 322 393 81.9


line stmt bran cond sub pod time code
1             package Test::Spec;
2 15     15   235180 use strict;
  15         136  
  15         895  
3 15     15   100 use warnings;
  15         33  
  15         575  
4 15     15   5479 use Test::Trap (); # load as early as possible to override CORE::exit
  15         762466  
  15         838  
5              
6             our $VERSION = '0.54';
7              
8 15     15   178 use parent 'Exporter';
  15         40  
  15         193  
9              
10 15     15   1140 use Carp ();
  15         41  
  15         321  
11 15     15   97 use Exporter ();
  15         39  
  15         285  
12 15     15   93 use File::Spec ();
  15         40  
  15         335  
13 15     15   8178 use Tie::IxHash ();
  15         73594  
  15         555  
14              
15 15     15   142 use constant { DEFINITION_PHASE => 0, EXECUTION_PHASE => 1 };
  15         41  
  15         5393  
16              
17             our $TODO;
18             our $Debug = $ENV{TEST_SPEC_DEBUG} || 0;
19              
20             our @EXPORT = qw(runtests
21             describe xdescribe context xcontext it xit they xthey
22             before after around yield spec_helper
23             *TODO share shared_examples_for it_should_behave_like );
24             our @EXPORT_OK = ( @EXPORT, qw(DEFINITION_PHASE EXECUTION_PHASE $Debug) );
25             our %EXPORT_TAGS = ( all => \@EXPORT_OK,
26             constants => [qw(DEFINITION_PHASE EXECUTION_PHASE)] );
27             our @CARP_NOT = ();
28              
29             our $_Current_Context;
30             our %_Package_Contexts;
31             our %_Package_Phase;
32             our %_Package_Tests;
33             our %_Shared_Example_Groups;
34             our $Yield = sub {
35             local @CARP_NOT = qw( Test::Spec );
36             Carp::croak "yield can be called only by around CODE";
37             };
38              
39             # Avoid polluting the Spec namespace by loading these other modules into
40             # what's essentially a mixin class. When you write "use Test::Spec",
41             # you'll get everything from Spec plus everything in ExportProxy. If you
42             # specify a list, the pool is limited to the stuff in @EXPORT_OK above.
43             {
44             package Test::Spec::ExportProxy;
45 15     15   151 use base qw(Exporter);
  15         43  
  15         3468  
46             BEGIN {
47 15     15   1406 eval "use Test::Deep 0.103 ()"; # check version and load export list
  15     15   7475  
  15         1006809  
  15         338  
48 15         87 Test::Deep->import(grep { $_ ne 'isa' } @Test::Deep::EXPORT);
  720         1596  
49             }
50 15     15   15163 use Test::More;
  15         84715  
  15         192  
51 15     15   6692 use Test::Trap;
  15         56  
  15         148  
52 15     15   15263 use Test::Spec::Mocks;
  15         59  
  15         131  
53             our @EXPORT_OK = (
54             @Test::More::EXPORT,
55             (grep { $_ ne 'isa' } @Test::Deep::EXPORT),
56             qw(trap $trap), # Test::Trap doesn't use Exporter
57             @Test::Spec::Mocks::EXPORT,
58             );
59             our @EXPORT = @EXPORT_OK;
60             our %EXPORT_TAGS = (all => \@EXPORT_OK);
61             }
62              
63             sub import {
64 44     44   308 my $class = shift;
65 44         145 my $callpkg = caller;
66              
67 44         284 strict->import;
68 44         506 warnings->import;
69              
70             # specific imports requested
71 44 100       194 if (@_) {
72 30         4138 $class->export_to_level(1, $callpkg, @_);
73 30         4445 return;
74             }
75              
76 14     14   117 eval qq{
  14         36  
  14         129  
  14         1254  
77             package $callpkg;
78             use parent 'Test::Spec';
79             # allow Test::Spec usage errors to be reported via Carp
80             our \@CARP_NOT = qw($callpkg);
81             };
82 14 50       84 die $@ if $@;
83 14         7303 Test::Spec::ExportProxy->export_to_level(1, $callpkg);
84 14         9612 $class->export_to_level(1, $callpkg);
85             }
86              
87             # PACKAGE->phase
88             # PACKAGE->phase(NEWPHASE)
89             sub phase {
90 17     17 0 5306 my $invocant = shift;
91 17   33     173 my $class = ref($invocant) || $invocant;
92 17 100       78 if (@_) {
93 15         58 $_Package_Phase{$class} = shift;
94             }
95 17 100       186 if (exists $_Package_Phase{$class}) {
96 16         306 return $_Package_Phase{$class};
97             }
98             else {
99 1         8 return $_Package_Phase{$class} = DEFINITION_PHASE;
100             }
101             }
102              
103             # PACKAGE->add_test(SUBNAME)
104             sub add_test {
105 128     128 0 247 my ($class,$test) = @_;
106 128   50     386 my $list = $_Package_Tests{$class} ||= [];
107 128         218 push @$list, $test;
108 128         308 return;
109             }
110              
111             # @subnames = PACKAGE->tests
112             sub tests {
113 143     143 0 275 my ($class) = @_;
114 143   100     452 my $list = $_Package_Tests{$class} ||= [];
115 143         344 return @$list;
116             }
117              
118             # runtests
119             # PACKAGE->runtests # @ARGV or $ENV{SPEC}
120             # PACKAGE->runtests(PATTERNS)
121             sub runtests {
122 15     15 1 2924 my $class = $_[0];
123 15 100       78 if (not defined $class) {
    50          
124 13         45 $class = caller;
125             }
126 2         36 elsif (not eval { $class->isa(__PACKAGE__) }) {
127 0         0 $class = caller;
128             }
129             else {
130 2         8 shift; # valid class, remove from arg stack.
131             }
132 15         560 $class->_materialize_tests;
133 15         180 $class->phase(EXECUTION_PHASE);
134              
135             my @which = @_ ? @_ :
136 15 50       135 $ENV{SPEC} ? ($ENV{SPEC}) : ();
    50          
137              
138 15         143 my @tests = $class->_pick_tests(@which);
139 15         109 return $class->_execute_tests( @tests );
140             }
141              
142             sub builder {
143             # this is a singleton.
144 139     139 0 841 Test::Builder->new;
145             }
146              
147             sub _pick_tests {
148 15     15   59 my ($class,@matchers) = @_;
149 15         64 my @tests = $class->tests;
150              
151 15         59 my $pattern = join("|", @matchers);
152 15         49 @tests = grep { $_->name =~ /$pattern/i } @tests;
  128         289  
153              
154 15         71 return @tests;
155             }
156              
157             sub _execute_tests {
158 15     15   74 my ($class,@tests) = @_;
159 15         64 for my $test (@tests) {
160 128         535 $test->run();
161             }
162              
163             # Ensure we don't keep any references to user variables so they go out
164             # of scope in a predictable fashion.
165 15         295 %_Package_Tests = %_Package_Contexts = ();
166              
167             # XXX: this doesn't play nicely with Test::NoWarnings and friends
168 15         172 $class->builder->done_testing;
169             }
170              
171             # it DESC => CODE
172             # it CODE
173             # it DESC
174             sub it(@) {
175 119     119 1 824096 my $package = caller;
176 119         192 my $code;
177 119 50 33     603 if (@_ && ref($_[-1]) eq 'CODE') {
178 119         208 $code = pop;
179             }
180 119         211 my $name = shift;
181 119 50 33     309 if (not ($code || $name)) {
182 0         0 Carp::croak "it() requires at least one of (description,code)";
183             }
184 119   50     241 $name ||= "behaves as expected (whatever that means)";
185 119         173 push @{ _autovivify_context($package)->tests }, {
  119         854  
186             name => $name,
187             code => $code,
188             todo => $TODO,
189             };
190 119         330 return;
191             }
192              
193             # alias "they" to "it", for describing behavior of multiple items
194             sub they(@);
195 15     15   4882 BEGIN { *they = \&it }
196              
197             # describe DESC => CODE
198             # describe CODE
199             sub describe(@) {
200 61     61 1 1968 my $package = caller;
201 61         152 my $code = pop;
202 61 50       212 if (ref($code) ne 'CODE') {
203 0         0 Carp::croak "expected subroutine reference as last argument";
204             }
205 61   33     204 my $name = shift || $package;
206              
207 61         108 my $container;
208 61 100       166 if ($_Current_Context) {
209 35         131 $container = $_Current_Context->context_lookup;
210             }
211             else {
212 26   66     152 $container = $_Package_Contexts{$package} ||= Test::Spec::_ixhash();
213             }
214              
215 61         428 __PACKAGE__->_accumulate_examples({
216             container => $container,
217             name => $name,
218             class => $package,
219             code => $code,
220             label => $name,
221             });
222             }
223              
224             # around CODE
225             sub around(&) {
226 3     3 1 29 my $package = caller;
227 3         7 my $code = pop;
228 3 50       11 if (ref($code) ne 'CODE') {
229 0         0 Carp::croak "expected subroutine reference as last argument";
230             }
231 3         9 my $context = _autovivify_context($package);
232 3         8 push @{ $context->around_blocks }, { code => $code };
  3         9  
233             }
234              
235             # yield
236             sub yield() {
237 10     10 1 74 $Yield->();
238             }
239              
240             # make context() an alias for describe()
241             sub context(@);
242 15     15   2445 BEGIN { *context = \&describe }
243              
244             # used to easily disable suites/specs during development
245             sub xit(@) {
246 0     0 1 0 local $TODO = '(disabled)';
247 0         0 it(@_);
248             }
249              
250             sub xthey(@) {
251 0     0 1 0 local $TODO = '(disabled)';
252 0         0 they(@_);
253             }
254              
255             sub xdescribe(@) {
256 0     0 1 0 local $TODO = '(disabled)';
257 0         0 describe(@_);
258             }
259              
260             # make xcontext() an alias for xdescribe()
261             sub xcontext(@);
262 15     15   23362 BEGIN { *xcontext = \&xdescribe }
263              
264             # shared_examples_for DESC => CODE
265             sub shared_examples_for($&) {
266 2     2 1 16 my $package = caller;
267 2         3 my ($name,$code) = @_;
268 2 50       5 if (not defined($name)) {
269 0         0 Carp::croak "expected example group name as first argument";
270             }
271 2 50       13 if (ref($code) ne 'CODE') {
272 0         0 Carp::croak "expected subroutine reference as last argument";
273             }
274              
275             __PACKAGE__->_accumulate_examples({
276 2         14 container => \%_Shared_Example_Groups,
277             name => $name,
278             class => undef, # shared examples are global
279             code => $code,
280             label => '',
281             });
282             }
283              
284             # used by both describe() and shared_examples_for() to build example
285             # groups in context
286             sub _accumulate_examples {
287 63     63   158 my ($klass,$args) = @_;
288 63         124 my $container = $args->{container};
289 63         121 my $name = $args->{name};
290 63         110 my $class = $args->{class};
291 63         115 my $code = $args->{code};
292 63         111 my $label = $args->{label};
293              
294 63         98 my $context;
295             # Don't clobber contexts of the same name, aggregate them.
296 63 100       349 if ($container->{$name}) {
297 2         23 $context = $container->{$name};
298             }
299             else {
300 61         756 $container->{$name} = $context = Test::Spec::Context->new;
301 61         1192 $context->name( $label );
302             # A context gets either a parent or a class. This is because the
303             # class should be inherited from the parent to support classless
304             # shared example groups.
305 61 100       141 if ($_Current_Context) {
306 36         89 $context->parent( $_Current_Context );
307             }
308             else {
309 25         85 $context->class( $class );
310             }
311             }
312              
313             # evaluate the context function, which will set up lexical variables and
314             # define tests and other contexts
315 63         261 $context->contextualize($code);
316             }
317              
318             # it_should_behave_like DESC
319             sub it_should_behave_like($) {
320 4     4 1 35 my ($name) = @_;
321 4 50       9 if (not defined($name)) {
322 0         0 Carp::croak "expected example_group_name as first argument";
323             }
324 4 50       7 if (!$_Current_Context) {
325 0         0 Carp::croak "it_should_behave_like can only be used inside a describe or shared_examples_for context";
326             }
327 4   33     12 my $context = $_Shared_Example_Groups{$name} ||
328             Carp::croak "unrecognized example group \"$name\"";
329              
330             # make a copy so we can assign the correct class name (via parent),
331             # which is needed for flattening the context into actual test
332             # functions later.
333 4         10 my $shim = $context->clone;
334 4         13 $shim->parent($_Current_Context);
335              
336             # add our shared_examples_for context as if it had been written inline
337             # as a describe() block
338 4         7 $_Current_Context->context_lookup->{"__shared_examples__:$name"} = $shim;
339             }
340              
341             # before CODE
342             # before all => CODE
343             # before each => CODE
344             sub before (@) {
345 28     28 1 331 my $package = caller;
346 28         50 my $code = pop;
347 28 50       77 if (ref($code) ne 'CODE') {
348 0         0 Carp::croak "expected subroutine reference as last argument";
349             }
350 28   100     75 my $type = shift || 'each';
351 28 50 66     103 if ($type ne 'each' && $type ne 'all') {
352 0         0 Carp::croak "before type should be one of 'each' or 'all'";
353             }
354 28         66 my $context = _autovivify_context($package);
355 28         46 push @{ $context->before_blocks }, { type => $type, code => $code };
  28         76  
356             }
357              
358             # after CODE
359             # after all => CODE
360             # after each => CODE
361             sub after (@) {
362 2     2 1 24 my $package = caller;
363 2         5 my $code = pop;
364 2 50       8 if (ref($code) ne 'CODE') {
365 0         0 Carp::croak "expected subroutine reference as last argument";
366             }
367 2   50     7 my $type = shift || 'each';
368 2 50 66     12 if ($type ne 'each' and $type ne 'all') {
369 0         0 Carp::croak "after type should be one of 'each' or 'all'";
370             }
371 2         5 my $context = _autovivify_context($package);
372 2         3 push @{ $context->after_blocks }, { type => $type, code => $code };
  2         9  
373             }
374              
375             # spec_helper FILESPEC
376             sub spec_helper ($) {
377 5     5 1 26 my $filespec = shift;
378 5         21 my ($callpkg,$callfile) = caller;
379 5         10 my $load_path;
380 5 100       44 if (File::Spec->file_name_is_absolute($filespec)) {
381 1         4 $load_path = $filespec;
382             }
383             else {
384 4         61 my ($callvol,$calldir,undef) = File::Spec->splitpath($callfile);
385 4         34 my (undef,$filedir,$filename) = File::Spec->splitpath($filespec);
386 4         36 my $newdir = File::Spec->catdir($calldir,$filedir);
387 4         43 $load_path = File::Spec->catpath($callvol,$newdir,$filename);
388             }
389 5         896 my $sub = eval "package $callpkg;\n" . q[sub {
390             my ($file,$origpath) = @_;
391             open(my $IN, "<", $file)
392             || die "could not open spec_helper '$origpath': $!";
393             defined(my $content = do { local $/; <$IN> })
394             || die "could not read spec_helper '$origpath': $!";
395             eval("# line 1 \"$origpath\"\n" . $content);
396             die "$@\n" if $@;
397             }];
398 5         131 $sub->($load_path,$filespec);
399             }
400              
401             sub share(\%) {
402 2     2 1 13 my $hashref = shift;
403 2         15 tie %$hashref, 'Test::Spec::SharedHash';
404             }
405              
406             sub _materialize_tests {
407 15     15   46 my $class = shift;
408 15         53 my $contexts = $_Package_Contexts{$class};
409 15 100 66     346 if (not $contexts && %$contexts) {
410 1         322 Carp::carp "no examples defined in spec package $class";
411 1         85 return;
412             }
413 14         343 for my $context (values %$contexts) {
414 25         407 $context->_materialize_tests();
415             }
416             }
417              
418             sub in_context {
419 262     262 0 670 my ($class,$context) = @_;
420 262 100       1322 if (!$_Current_Context) {
    100          
    50          
421 25         107 return '';
422             }
423             elsif ($context == $_Current_Context) {
424 72         324 return 1;
425             }
426             elsif ($context->ancestor_of($_Current_Context)) {
427 0         0 return 1;
428             }
429             else {
430 165         1054 return '';
431             }
432             }
433              
434             # NOT a method, just a subroutine that takes a package name.
435             sub _autovivify_context {
436 152     152   298 my ($package) = @_;
437 152 50       315 if ($_Current_Context) {
438 152         460 return $_Current_Context;
439             }
440             else {
441 0         0 my $name = ''; # unnamed context
442 0   0     0 return $_Package_Contexts{$package}{$name} ||=
443             Test::Spec::Context->new({ name => $name, class => $package, parent => undef });
444             }
445             }
446              
447             # Public interface.
448             sub current_context {
449 78     78 0 374 $_Current_Context
450             }
451              
452             sub contexts {
453 26     26 0 1712 my ($class) = @_;
454 26 50       63 my @ctx = values %{ $_Package_Contexts{$class} || {} };
  26         144  
455 26 50       1270 return wantarray ? @ctx : \@ctx;
456             }
457              
458             sub _ixhash {
459 81     81   541 tie my %h, 'Tie::IxHash';
460 81         1606 \%h;
461             }
462              
463             # load context implementation
464             require Test::Spec::Context;
465             require Test::Spec::SharedHash;
466              
467             1;
468              
469             =head1 NAME
470              
471             Test::Spec - Write tests in a declarative specification style
472              
473             =head1 SYNOPSIS
474              
475             use Test::Spec; # automatically turns on strict and warnings
476              
477             describe "A date" => sub {
478              
479             my $date;
480              
481             describe "in a leap year" => sub {
482              
483             before each => sub {
484             $date = DateTime->new(year => 2000, month => 2, day => 28);
485             };
486              
487             it "should know that it is in a leap year" => sub {
488             ok($date->is_leap_year);
489             };
490              
491             it "should recognize Feb. 29" => sub {
492             is($date->add(days => 1)->day, 29);
493             };
494              
495             };
496              
497             describe "not in a leap year" => sub {
498             before each => sub {
499             $date = DateTime->new(year => 2001, month => 2, day => 28);
500             };
501              
502             it "should know that it is NOT in a leap year" => sub {
503             ok(!$date->is_leap_year);
504             };
505              
506             it "should NOT recognize Feb. 29" => sub {
507             is($date->add(days => 1)->day, 1);
508             };
509             };
510              
511             };
512              
513             runtests unless caller;
514              
515             # Generates the following output:
516             # ok 1 - A date in a leap year should know that it is in a leap year
517             # ok 2 - A date in a leap year should recognize Feb. 29
518             # ok 3 - A date not in a leap year should know that it is NOT in a leap year
519             # ok 4 - A date not in a leap year should NOT recognize Feb. 29
520             # 1..4
521              
522              
523             =head1 DESCRIPTION
524              
525             This is a declarative specification-style testing system for behavior-driven
526             development (BDD) in Perl. The tests (a.k.a. examples) are named with strings
527             instead of subroutine names, so your fingers will suffer less fatigue from
528             underscore-itis, with the side benefit that the test reports are more legible.
529              
530             This module is inspired by and borrows heavily from L,
531             a BDD tool for the Ruby programming language.
532              
533             =head2 EXPORTS
534              
535             When given B (i.e. C), this class will export:
536              
537             =over 4
538              
539             =item * Spec definition functions
540              
541             These are the functions you will use to define behaviors and run your specs:
542             C, C, C, C, C, C, C,
543             C, C, and C.
544              
545             =item * The stub/mock functions in L.
546              
547             =item * Everything that L normally exports
548              
549             This includes C, C and friends. You'll use these to assert
550             correct behavior.
551              
552             =item * Everything that L normally exports
553              
554             More assertions including C.
555              
556             =item * Everything that C normally exports
557              
558             The C function, which let you test behaviors that call C and
559             other hard things like that. "A block eval on steroids."
560              
561             =back
562              
563             If you specify an import list, only functions directly from C
564             (those documented below) are available.
565              
566             =head2 FUNCTIONS
567              
568             =over 4
569              
570             =item runtests
571              
572             =item runtests(@patterns)
573              
574             Runs all the examples whose descriptions match one of the (non case-sensitive)
575             regular expressions in C<@patterns>. If C<@patterns> is not provided,
576             runs I examples. The environment variable "SPEC" will be used as a
577             default pattern if present.
578              
579             If called as a function (i.e. I a method call with "->"), C
580             will autodetect the package from which it is called and run that
581             package's examples. A useful idiom is:
582              
583             runtests unless caller;
584              
585             which will run the examples when the file is loaded as a script (for example,
586             by running it from the command line), but not when it is loaded as a module
587             (with C or C).
588              
589             =item describe DESCRIPTION => CODE
590              
591             =item describe CODE
592              
593             Defines a specification context under which examples and more
594             descriptions can be defined. All examples I come inside a C
595             block.
596              
597             =over 4
598              
599             =item C blocks can be nested to DRY up your specs.
600              
601             For large specifications, C blocks can save you a lot of duplication:
602              
603             describe "A User object" => sub {
604             my $user;
605             before sub {
606             $user = User->new;
607             };
608             describe "from a web form" => sub {
609             before sub {
610             $user->init_from_tree({ username => "bbill", ... });
611             };
612             it "should read its attributes from the form";
613             describe "when saving" => sub {
614             it "should require a unique username";
615             it "should require a password";
616             };
617             };
618             };
619              
620             The setup work done in each C block cascades from one level
621             to the next, so you don't have to make a call to some
622             initialization function manually in each test. It's done
623             automatically based on context.
624              
625             =item Using describe blocks improves legibility without requiring more typing.
626              
627             The name of the context will be included by default in the
628             success/failure report generated by Test::Builder-based testing methods (e.g.
629             Test::More's ok() function). For an example like this:
630              
631             describe "An unladen swallow" => sub {
632             it "has an airspeed of 11 meters per second" => sub {
633             is($swallow->airspeed, "11m/s");
634             };
635             };
636              
637             The output generated is:
638              
639             ok 1 - An unladen swallow has an airspeed of 11 meters per second
640              
641             Contrast this to the following test case to generate the same output:
642              
643             sub unladen_swallow_airspeed : Test {
644             is($swallow->airspeed, "11m/s",
645             "An unladen swallow has an airspeed of 11 meters per second");
646             }
647              
648             =back
649              
650             C blocks execute in the order in which they are defined. Multiple
651             C blocks with the same name are allowed. They do not replace each
652             other, rather subsequent Cs extend the existing one of the same
653             name.
654              
655             =item context
656              
657             An alias for C.
658              
659             =item xdescribe
660              
661             Specification contexts may be disabled by calling C instead of
662             C. All examples inside an C are reported as
663             "# TODO (disabled)", which prevents Test::Harness/prove from counting them
664             as failures.
665              
666             =item xcontext
667              
668             An alias for C.
669              
670             =item it SPECIFICATION => CODE
671              
672             =item it CODE
673              
674             =item it TODO_SPECIFICATION
675              
676             Defines an example to be tested. Despite its awkward name, C allows
677             a natural (in my opinion) way to describe expected behavior:
678              
679             describe "A captive of Buffalo Bill" => sub {
680             it "puts the lotion on its skin" => sub {
681             ...
682             };
683             it "puts the lotion in the basket"; # TODO
684             };
685              
686             If a code reference is not passed, the specification is assumed to be
687             unimplemented and will be reported as "TODO (unimplemented)" in the test
688             results (see L. TODO tests report as skipped,
689             not failed.
690              
691             =item they SPECIFICATION => CODE
692              
693             =item they CODE
694              
695             =item they TODO_SPECIFICATION
696              
697             An alias for L. This is useful for describing behavior for groups of
698             items, so the verb agrees with the noun:
699              
700             describe "Captives of Buffalo Bill" => sub {
701             they "put the lotion on their skin" => sub {
702             ...
703             };
704             they "put the lotion in the basket"; # TODO
705             };
706              
707             =item xit/xthey
708              
709             Examples may be disabled by calling xit()/xthey() instead of it()/they().
710             These examples are reported as "# TODO (disabled)", which prevents
711             Test::Harness/prove from counting them as failures.
712              
713             =item before each => CODE
714              
715             =item before all => CODE
716              
717             =item before CODE
718              
719             Defines code to be run before tests in the current describe block are
720             run. If "each" is specified, CODE will be re-executed for every test in
721             the context. If "all" is specified, CODE will only be executed before
722             the first test.
723              
724             The default is "each", due to this logic presented in RSpec's documentation:
725              
726             I<"It is very tempting to use before(:all) and after(:all) for situations
727             in which it is not appropriate. before(:all) shares some (not all) state
728             across multiple examples. This means that the examples become bound
729             together, which is an absolute no-no in testing. You should really only
730             ever use before(:all) to set up things that are global collaborators but
731             not the things that you are describing in the examples.>
732              
733             I
734             Every example that accesses the database should start with a clean
735             slate, otherwise the examples become brittle and start to lose their
736             value with false negatives and, worse, false positives.">
737              
738             (L)
739              
740             There is no restriction on having multiple before blocks. They will run in
741             sequence within their respective "each" or "all" groups. C
742             blocks run before C blocks.
743              
744             =item after each => CODE
745              
746             =item after all => CODE
747              
748             =item after CODE
749              
750             Like C, but backwards. Runs CODE after each or all tests,
751             respectively. The default is "each".
752              
753             C blocks run I C blocks.
754              
755             =item around CODE
756              
757             Defines code to be run around tests in the current describe block are
758             run. This code must call C..
759              
760             our $var = 0;
761              
762             describe "Something" => sub {
763             around {
764             local $var = 1;
765             yield;
766             };
767              
768             it "should have localized var" => sub {
769             is $var, 1;
770             };
771             };
772              
773             This CODE will run around each example.
774              
775             =item yield
776              
777             Runs examples in context of C block.
778              
779             =item shared_examples_for DESCRIPTION => CODE
780              
781             Defines a group of examples that can later be included in
782             C blocks or other C blocks. See
783             L.
784              
785             Example group names are B, but example groups can be defined at any
786             level (i.e. they can be defined in the global context, or inside a "describe"
787             block).
788              
789             my $browser;
790             shared_examples_for "all browsers" => sub {
791             it "should open a URL" => sub { ok($browser->open("http://www.google.com/")) };
792             ...
793             };
794             describe "Firefox" => sub {
795             before all => sub { $browser = Firefox->new };
796             it_should_behave_like "all browsers";
797             it "should have firefox features";
798             };
799             describe "Safari" => sub {
800             before all => sub { $browser = Safari->new };
801             it_should_behave_like "all browsers";
802             it "should have safari features";
803             };
804              
805             =item it_should_behave_like DESCRIPTION
806              
807             Asserts that the thing currently being tested passes all the tests in
808             the example group identified by DESCRIPTION (having previously been
809             defined with a C block). In essence, this is like
810             copying all the tests from the named C block into
811             the current context. See L and
812             L.
813              
814             =item share %HASH
815              
816             Registers C<%HASH> for sharing data between tests and example groups.
817             This lets you share variables with code in different lexical scopes
818             without resorting to using package (i.e. global) variables or jumping
819             through other hoops to circumvent scope problems.
820              
821             Every hash that is Cd refers to the B. Sharing a hash
822             will make its existing contents inaccessible, because afterwards it
823             contains the same data that all other shared hashes contain. The result
824             is that you get a hash with global semantics but with lexical scope
825             (assuming C<%HASH> is a lexical variable).
826              
827             There are a few benefits of using C over using a "regular"
828             global hash. First, you don't have to decide what package the hash will
829             belong to, which is annoying when you have specs in several packages
830             referencing the same shared examples. You also don't have to clutter
831             your examples with colons for fully-qualified names. For example, at my
832             company our specs go in the "ICA::TestCase" hierarchy, and
833             "$ICA::TestCase::Some::Package::variable" is exhausting to both the eyes
834             and the hands. Lastly, using C allows C to provide
835             this functionality without deciding on the variable name for you (and
836             thereby potentially clobbering one of your variables).
837              
838             share %vars; # %vars now refers to the global share
839             share my %vars; # declare and share %vars in one step
840              
841             =item spec_helper FILESPEC
842              
843             Loads the Perl source in C into the current spec's package. If
844             C is relative (no leading slash), it is treated as relative to
845             the spec file (i.e. B the currently running script). This lets you
846             keep helper scripts near the specs they are used by without exercising
847             your File::Spec skills in your specs.
848              
849             # in foo/spec.t
850             spec_helper "helper.pl"; # loads foo/helper.pl
851             spec_helper "helpers/helper.pl"; # loads foo/helpers/helper.pl
852             spec_helper "/path/to/helper.pl"; # loads /path/to/helper.pl
853              
854             =back
855              
856             =head2 Shared example groups
857              
858             This feature comes straight out of RSpec, as does this documentation:
859              
860             You can create shared example groups and include those groups into other
861             groups.
862              
863             Suppose you have some behavior that applies to all editions of your
864             product, both large and small.
865              
866             First, factor out the "shared" behavior:
867              
868             shared_examples_for "all editions" => sub {
869             it "should behave like all editions" => sub {
870             ...
871             };
872             };
873              
874             then when you need to define the behavior for the Large and Small
875             editions, reference the shared behavior using the
876             C function.
877              
878             describe "SmallEdition" => sub {
879             it_should_behave_like "all editions";
880             };
881              
882             describe "LargeEdition" => sub {
883             it_should_behave_like "all editions";
884             it "should also behave like a large edition" => sub {
885             ...
886             };
887             };
888              
889             C will search for an example group by its
890             description string, in this case, "all editions".
891              
892             Shared example groups may be included in other shared groups:
893              
894             shared_examples_for "All Employees" => sub {
895             it "should be payable" => sub {
896             ...
897             };
898             };
899              
900             shared_examples_for "All Managers" => sub {
901             it_should_behave_like "All Employees";
902             it "should be bonusable" => sub {
903             ...
904             };
905             };
906              
907             describe Officer => sub {
908             it_should_behave_like "All Managers";
909             it "should be optionable";
910             };
911              
912             # generates:
913             ok 1 - Officer should be optionable
914             ok 2 - Officer should be bonusable
915             ok 3 - Officer should be payable
916              
917             =head3 Refactoring into files
918              
919             If you want to factor specs into separate files, variable scopes can be
920             tricky. This is especially true if you follow the recommended pattern
921             and give each spec its own package name. C offers a couple
922             of functions that ease this process considerably: L
923             and L.
924              
925             Consider the browsers example from C. A real
926             browser specification would be large, so putting the specs for all
927             browsers in the same file would be a bad idea. So let's say we create
928             C for the shared examples, and give Safari and Firefox
929             C and C, respectively.
930              
931             The problem then becomes: how does the code in C access
932             the C<$browser> variable? In L CODE>,
933             C<$browser> is a lexical variable that is in scope for all the examples.
934             But once those examples are split into multiple files, you would have to
935             use either package global variables or worse, come up with some other
936             hack. This is where C and C come in.
937              
938             # safari.t
939             package Testcase::Safari;
940             use Test::Spec;
941             spec_helper 'all_browsers.pl';
942              
943             describe "Safari" => sub {
944             share my %vars;
945             before all => sub { $vars{browser} = Safari->new };
946             it_should_behave_like "all browsers";
947             it "should have safari features";
948             };
949              
950             # firefox.t
951             package Testcase::Firefox;
952             use Test::Spec;
953             spec_helper 'all_browsers.pl';
954              
955             describe "Firefox" => sub {
956             share my %vars;
957             before all => sub { $vars{browser} = Firefox->new };
958             it_should_behave_like "all browsers";
959             it "should have firefox features";
960             };
961              
962             # in all_browsers.pl
963             shared_examples_for "all browsers" => sub {
964             # doesn't have to be the same name!
965             share my %t;
966             it "should open a URL" => sub {
967             ok $t{browser}->open("http://www.google.com/");
968             };
969             ...
970             };
971              
972             =head2 Order of execution
973              
974             This example, shamelessly adapted from the RSpec website, gives an overview of
975             the order in which examples run, with particular attention to C and
976             C.
977              
978             describe Thing => sub {
979             before all => sub {
980             # This is run once and only once, before all of the examples
981             # and before any before("each") blocks.
982             };
983              
984             before each => sub {
985             # This is run before each example.
986             };
987              
988             before sub {
989             # "each" is the default, so this is the same as before("each")
990             };
991              
992             it "should do stuff" => sub {
993             ...
994             };
995              
996             it "should do more stuff" => sub {
997             ...
998             };
999              
1000             after each => sub {
1001             # this is run after each example
1002             };
1003              
1004             after sub {
1005             # "each" is the default, so this is the same as after("each")
1006             };
1007              
1008             after all => sub {
1009             # this is run once and only once after all of the examples
1010             # and after any after("each") blocks
1011             };
1012              
1013             };
1014              
1015             =head1 SEE ALSO
1016              
1017             L, L, L, L,
1018             L.
1019              
1020             The mocking and stubbing tools are in L.
1021              
1022             =head1 AUTHOR
1023              
1024             Philip Garrett
1025              
1026             =head1 CONTRIBUTING
1027              
1028             The source code for Test::Spec lives on L
1029              
1030             If you want to contribute a patch, fork my repository, make your change,
1031             and send me a pull request.
1032              
1033             =head1 SUPPORT
1034              
1035             If you have found a defect or have a feature request please report an
1036             issue at https://github.com/kingpong/perl-Test-Spec/issues. For help
1037             using the module, standard Perl support channels like
1038             L and
1039             L
1040             are probably your best bet.
1041              
1042             =head1 COPYRIGHT & LICENSE
1043              
1044             Copyright (c) 2010-2011 by Informatics Corporation of America.
1045              
1046             This program is free software; you can redistribute it and/or modify it
1047             under the same terms as Perl itself.
1048              
1049             =cut