[mocha-developer] Stubbing constructiors

James Mead jamesmead44 at gmail.com
Thu Dec 14 09:15:36 EST 2006


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.

-- 
James.
http://blog.floehopper.org


More information about the mocha-developer mailing list