s/make_immutable/metaclass->make_immutable/
[gitmo/Moose.git] / t / 010_basics / 012_rebless.t
CommitLineData
af3c1f96 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Test::More tests => 13;
7use Test::Exception;
8use Scalar::Util 'blessed';
9
10BEGIN {
11 use_ok('Moose');
12 use_ok("Moose::Util::TypeConstraints");
13}
14
15subtype 'Positive'
16 => as 'Num'
17 => where { $_ > 0 };
18
19{
20 package Parent;
21 use Moose;
22
23 has name => (
24 is => 'rw',
25 isa => 'Str',
26 );
27
28 has lazy_classname => (
29 is => 'ro',
30 lazy => 1,
31 default => sub { "Parent" },
32 );
33
34 has type_constrained => (
35 is => 'rw',
36 isa => 'Num',
37 default => 5.5,
38 );
39
40 package Child;
41 use Moose;
42 extends 'Parent';
43
44 has '+name' => (
45 default => 'Junior',
46 );
47
48 has '+lazy_classname' => (
49 default => sub { "Child" },
50 );
51
52 has '+type_constrained' => (
53 isa => 'Int',
54 default => 100,
55 );
56}
57
58my $foo = Parent->new;
59my $bar = Parent->new;
60
61is(blessed($foo), 'Parent', 'Parent->new gives a Parent object');
62is($foo->name, undef, 'No name yet');
63is($foo->lazy_classname, 'Parent', "lazy attribute initialized");
64lives_ok { $foo->type_constrained(10.5) } "Num type constraint for now..";
65
66# try to rebless, except it will fail due to Child's stricter type constraint
688fcdda 67throws_ok { Child->meta->rebless_instance($foo) }
68qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' failed with value 10\.5/,
69'... this failed cause of type check';
70throws_ok { Child->meta->rebless_instance($bar) }
71qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' failed with value 5\.5/,
72'... this failed cause of type check';;
af3c1f96 73
74$foo->type_constrained(10);
75$bar->type_constrained(5);
76
a4154081 77Child->meta->rebless_instance($foo);
78Child->meta->rebless_instance($bar);
af3c1f96 79
80is(blessed($foo), 'Child', 'successfully reblessed into Child');
81is($foo->name, 'Junior', "Child->name's default came through");
82
83is($foo->lazy_classname, 'Parent', "lazy attribute was already initialized");
84is($bar->lazy_classname, 'Child', "lazy attribute just now initialized");
85
688fcdda 86throws_ok { $foo->type_constrained(10.5) }
87qr/^Attribute \(type_constrained\) does not pass the type constraint because\: Validation failed for 'Int' failed with value 10\.5/,
88'... this failed cause of type check';