wrote roles recipe 3 - applying a role to an object instance
[gitmo/Moose.git] / t / 000_recipes / roles / 003_instance_application.t
1 use strict;
2 use warnings;
3
4 use Test::More tests => 2;
5
6
7 {
8     # Not in the recipe, but needed for writing tests.
9     package Employee;
10
11     use Moose;
12
13     has 'name' => (
14         is       => 'ro',
15         isa      => 'Str',
16         required => 1,
17     );
18
19     has 'work' => (
20         is        => 'rw',
21         isa       => 'Str',
22         predicate => 'has_work',
23     );
24 }
25
26 {
27     package MyApp::Role::Job::Manager;
28
29     use List::Util qw( first );
30
31     use Moose::Role;
32
33     has 'employees' => (
34         is  => 'rw',
35         isa => 'ArrayRef[Employee]',
36     );
37
38     sub assign_work {
39         my $self = shift;
40         my $work = shift;
41
42         my $employee = first { !$_->has_work } @{ $self->employees };
43
44         die 'All my employees have work to do!' unless $employee;
45
46         $employee->work($work);
47     }
48 }
49
50 {
51     my $lisa = Employee->new( name => 'Lisa' );
52     MyApp::Role::Job::Manager->meta->apply($lisa);
53
54     ok( $lisa->does('MyApp::Role::Job::Manager'),
55         'lisa now does the manager role' );
56
57     my $homer = Employee->new( name => 'Homer' );
58     my $bart  = Employee->new( name => 'Bart' );
59     my $marge = Employee->new( name => 'Marge' );
60
61     $lisa->employees( [ $homer, $bart, $marge ] );
62     $lisa->assign_work('mow the lawn');
63
64     is( $homer->work, 'mow the lawn',
65         'homer was assigned a task by lisa' );
66 }