in reply to Re: Mocking a method defined in a Moo Role
in thread Mocking a method defined in a Moo Role

I was able to mock the role, but it's not nice. It seems tools for handling roles in tests aren't there, yet (i.e. there's no does_ok ).
#! /usr/bin/perl use Test::Spec; require MyClass; # No use! my $role_foo; { package MyRole; use Moo::Role; sub foo { $role_foo } } describe MyClass => sub { my $o; before each => sub { $o = 'MyClass'->new; }; it 'instantiates' => sub { isa_ok $o, 'MyClass'; }; it 'returns false' => sub { $role_foo = 'false'; is $o->foo('whatever'), 'false'; }; it "isn't sure" => sub { $role_foo = 'true'; is $o->foo('whatever'), 'probably'; }; }; runtests();

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^3: Mocking a method defined in a Moo Role
by PopeFelix (Beadle) on Jun 24, 2016 at 17:59 UTC
    That's not working for me either, and it seems like it should. Here's the sketch I'm using:

    MyRole.pm

    package MyRole; use Moo::Role; sub foo { return 'bar'; } 1;

    rolesketch.pl

    use 5.016; package MyClass; use Moo; use FindBin qw($Bin); use lib $Bin; with 'MyRole'; around foo => sub { my ($orig, $self) = @_; return 'Wrapped ' . $self->$orig; }; package main; package MyRole { sub foo { return 'baz' }; }; my $obj = MyClass->new; my $res = $obj->foo; if ($res =~ /baz$/) { say qq{OK, got $res}; } else { say qq{Not OK, got $res}; }

      Thanks to mst on #moose:

      MyClass.pm

      package MyClass; use Moo; use FindBin qw($Bin); use lib $Bin; with 'MyRole'; around foo => sub { my ($orig, $self) = @_; return 'Wrapped ' . $self->$orig; };

      rolesketch.pl

      use 5.016; use FindBin qw($Bin); use lib qq($Bin); require MyRole; our $orig = MyRole->can('foo'); no warnings 'redefine'; *MyRole::foo = sub { goto &$orig }; { local $orig = sub {'baz'}; require MyClass; my $obj = MyClass->new; my $res = $obj->foo; if ( $res =~ /baz$/ ) { say qq{OK, got $res}; } else { say qq{Not OK, got $res}; } }
      The following line is missing in MyRole:
      use Moo::Role;

      Also, foo and call are different subs.

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
        Thanks, I corrected that.