[rspec-users] Mocking base class methods

Tobi listaccount at e-tobi.net
Sat Feb 21 06:31:05 EST 2009


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.

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


More information about the rspec-users mailing list