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