File Coverage

blib/lib/Test/Spec.pm
Criterion Covered Total %
statement 195 215 90.7
branch 41 60 68.3
condition 20 40 50.0
subroutine 42 45 93.3
pod 12 19 63.1
total 310 379 81.7


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