Mouse::Util::does_role() respects $thing->does() method
[gitmo/Mouse.git] / t / 001_mouse / 016-trigger.t
CommitLineData
c3398f5b 1#!/usr/bin/env perl
2use strict;
3use warnings;
8ab2c6ab 4use Test::More;
eab81545 5use Test::Exception;
c3398f5b 6
7my @trigger;
8
9do {
10 package Class;
11 use Mouse;
12
13 has attr => (
14 is => 'rw',
15 default => 10,
16 trigger => sub {
25431bc4 17 my ($self, $value) = @_;
18 push @trigger, [$self, $value];
c3398f5b 19 },
20 );
21
8ab2c6ab 22 has foobar => ( # from Net::Google::DataAPI
23 is => 'rw',
24 isa => 'Str',
25
26 lazy => 1,
27 trigger => sub{ $_[0]->update },
28 default => sub{ 'piyo' },
29
30 clearer => 'clear_foobar',
31 );
32
33 sub update {
34 my($self) = @_;
35 $self->clear_foobar;
36 }
37
84731080 38 ::lives_ok {
6c5498d0 39 has not_error => (
c3398f5b 40 is => 'ro',
41 trigger => sub { },
42 );
84731080 43 } "it's no longer an error to have trigger on a readonly attribute";
6c5498d0 44
45 ::throws_ok {
46 has error => (
47 is => 'ro',
48 trigger => [],
49 );
844fa049 50 } qr/Trigger must be a CODE ref on attribute \(error\)/;
c3398f5b 51};
52
53can_ok(Class => 'attr');
54
55my $object = Class->new;
56is(@trigger, 0, "trigger not called yet");
57
58is($object->attr, 10, "default value");
59is(@trigger, 0, "trigger not called on read");
60
61is($object->attr(50), 50, "setting the value");
62is(@trigger, 1, "trigger was called on read");
25431bc4 63is_deeply([splice @trigger], [[$object, 50]], "correct arguments to trigger in the accessor");
c3398f5b 64
8ab2c6ab 65is($object->foobar, 'piyo');
25431bc4 66lives_ok { $object->foobar('baz') } "triggers that clear the attr";
67
8ab2c6ab 68is($object->foobar, 'piyo', "call clearer in triggers");
69
c3398f5b 70my $object2 = Class->new(attr => 100);
71is(@trigger, 1, "trigger was called on new with the attribute specified");
25431bc4 72is_deeply([splice @trigger], [[$object2, 100]], "correct arguments to trigger in the constructor");
c3398f5b 73
8ab2c6ab 74done_testing;