[rspec-users] Mocking base class methods

Zach Dennis zach.dennis at gmail.com
Sat Feb 21 14:48:21 EST 2009


On Sat, Feb 21, 2009 at 6:31 AM, Tobi <listaccount at e-tobi.net> wrote:
> Hi!
>
> I need to write some wrapper classes, that derive from SWIG generated
> proxy classes for some C/C++ extensions.
>
> The Ruby wrapper classes need to do a lot of 'super' calls to the base
> classes generated by SWIG.
>
> The question is: Is there any way to make RSpec mock a base class and
> record/verify that certain methods on a base class are called?
>
> As long as the methods in the derived class have different names this is
> no problem, but otherwise it doesn't seem to be possible - at least not
> with RSpec's mocking/stubbing facilities, does it?
>
> I see other ways to do this, like wrapping an instance of the Swig class
> instead of deriving from it or writing some custom mocking code that fakes
> the base class e.g. with define_method, but I'm especially asking if this
> is possible with RSpec.

+1 to composition over inheritance here. Mocking at different layers
of an inheritance hierarchy sounds like trouble and screams to pull
that thing apart. Composition will allow you to separate an
inheritance hierarchy (if you do need one) from the swig base classes,
and it provides a clean separation between the swig stuff and your
application stuff.

>
> thx,
>
> Tobias
>
> module Swig
>  class Base
>    def initialize(arg)
>    end
>
>    def do_something(arg)
>    end
>  end
> end
>
> module Wrapper
>  class Derived << Swig::Base
>    def initialize(arg)
>      super(arg)
>      yield(self) if block_given?
>    end
>
>    def do_something(arg)
>      do_something(arg)
>      # additional behaviour here
>    end
>  end
> end
>
> describe Wrapper::Derived do
>  it 'should initialize the base class with the same argument' do
>    # No idea, how to mock Base.initialize() here
>  end
>
>  it 'should do something with the base class when doing something' do
>    # No idea, how to mock Base.do_something() here
>  end
> end
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>



-- 
Zach Dennis
http://www.continuousthinking.com
http://www.mutuallyhuman.com


More information about the rspec-users mailing list