Added support for fancy triggers, and a test.
[gitmo/Moose.git] / t / 020_attributes / 004_attribute_triggers.t
index b5cf34e..e4088a2 100644 (file)
@@ -5,7 +5,7 @@ use warnings;
 
 use Scalar::Util 'isweak';
 
-use Test::More tests => 26;
+use Test::More tests => 43;
 use Test::Exception;
 
 BEGIN {
@@ -102,19 +102,92 @@ BEGIN {
     ok(isweak($baz->{foo}), '... baz.foo is a weak reference');
 }
 
+# before/around/after triggers
+{
+    package Fweet;
+    use Moose;
+
+    has calls => (
+        is      => 'ro',
+        isa     => 'ArrayRef',
+        default => sub {[]},
+    );
+
+    sub called {
+        my ($self, $str, @args) = @_;
+        push(@{$self->calls}, $str);
+    }
+
+    has noise => (
+        is => 'rw',
+        default => 'Sartak',
+        trigger => {
+            before => sub {
+                $_[0]->called('before');
+            },
+            around => sub {
+                my ($ori, $self, $val, @whatever) = @_;
+                $self->called('around');
+                $ori->($self, $val.'-diddly', @whatever);
+            },
+            after => sub {
+                $_[0]->called('after');
+            },
+        },
+    );
+}
+
+sub fancy_trigger_tests
+{
+    my $type = shift;
+    my $blah;
+    ::lives_ok {
+        $blah = Fweet->new;
+    } "... $type constructor";
+    my $expected_calls = [qw(before around after)];
+
+    is_deeply($blah->calls, $expected_calls, "$type default triggered");
+    is($blah->noise, 'Sartak-diddly', "$type default around modified value");
+    @{$blah->calls} = ();
+
+    $blah->noise('argle-bargle');
+    is_deeply($blah->calls, $expected_calls, "$type set triggered");
+    is($blah->noise, 'argle-bargle-diddly', "$type set around modified value");
+
+    $blah = Fweet->new(noise => 'woot');
+    is_deeply($blah->calls, $expected_calls, "$type constructor triggered");
+    is($blah->noise, 'woot-diddly', "$type constructor around modified value");
+}
+
+{
+  fancy_trigger_tests('normal');
+  ::lives_ok {
+    Fweet->meta->make_immutable;
+  } '... make_immutable works';
+  fancy_trigger_tests('inline');
+}
+
 # some errors
 
 {
     package Bling;
     use Moose;
+
+    ::dies_ok {
+        has('bling' => (is => 'rw', trigger => {FAIL => sub {}}));
+    } '... hash specifier has to be before/around/after';
+
+    ::dies_ok {
+        has('bling' => (is => 'rw', trigger => {around => 'FAIL'}));
+    } '... hash specifier value must be CODE ref';
     
     ::dies_ok { 
         has('bling' => (is => 'rw', trigger => 'Fail'));
-    } '... a trigger must be a CODE ref';
+    } '... a trigger must be a CODE or HASH ref';
     
     ::dies_ok { 
         has('bling' => (is => 'rw', trigger => []));
-    } '... a trigger must be a CODE ref';    
+    } '... a trigger must be a CODE or HASH ref';    
 }