[mocha-developer] Stubbing constructiors
Tomas Pospisek
tpo2 at sourcepole.ch
Thu Dec 14 10:06:48 EST 2006
Quoting James Mead <jamesmead44 at gmail.com>:
> On 14/12/06, Tomas Pospisek <tpo2 at sourcepole.ch> wrote:
> > This works:
> >
> > class X
> > def X.initialize( stuff )
> > end
> > end
> >
> > X.initialize("bla")
> >
> >
> > However stubbing it doesn,t:
> >
> > require 'test/unit'
> > require 'stubba'
> >
> > class X
> > def X.initialize( stuff )
> > end
> > end
> >
> > class XTest < Test::Unit::TestCase
> > def test_
> > X.stubs(:initialize).with("bla")
> > X.initialize("bla")
> > end
> > end
> >
> > Ruby lets me know that:
> >
> > Loaded suite /tmp/foo
> > Started
> > E(eval):1: warning: removing `initialize' may cause serious problem
> >
> > Finished in 0.002625 seconds.
> >
> > 1) Error:
> > test_(XTest):
> > NoMethodError: private method `initialize' called for X:Class
> > /tmp/kak.rb:12:in `test_'
> >
> > 1 tests, 0 assertions, 0 failures, 1 errors
> >
> > Routing around the problem is possible:
> >
> > require 'test/unit'
> > require 'stubba'
> >
> > class X
> > def X.initialize( stuff )
> > end
> > end
> >
> > class XTest < Test::Unit::TestCase
> > def test_
> > X.stubs(:initialize).with("bla")
> > X.public_class_method :initialize
> > X.initialize("bla")
> > end
> > end
>
> Not being able to stub private methods is a known issue (see elsewhere
> on this mailing list). We may add functionality to allow it, but even
> if we do I suspect we will want to make the API explicitly express the
> fact that you are stubbing a private method which means you are
> tightly coupling your test to the implementation details of the class.
>
> Have you considered stubbing the "new" method which is a public
> method? It is effectively an implementation detail of the Object class
> that the new method calls the initialize method.
Um, well, kind of. The above is of course just a "mock" of the real situation
I'm confronted with in my code and there I really do have a *class* method
named "initialize" that I call just like that. That is I am initializing the
class and not instantiating an object, in which case, as you correctly point
out I'd better stub "new".
It smells a bit, yes, unfortunately I'm only at the "aspiring to become a Ruby
wizzard" stage...
Thanks,
*t
----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.
More information about the mocha-developer
mailing list