[mocha-developer] Mocking class methods: documentation suggestion

Ken Harris kengruven at gmail.com
Thu Apr 24 19:15:09 EDT 2008


Hi Mocha people,

I'm just starting to use Mocha, and I had some trouble, so I thought
I'd share my experiences so other people don't have to go through what
I did.

New mocks worked just fine (a=mock(); a.expects(:b), ...) -- very
cool.  But I wanted to mess with class methods, like Time.now, and it
was not happy with that for some reason:

    $ irb
    >> require 'mocha'
    => true
    >> Time.stubs(:now).returns("pancakes")
    NoMethodError: undefined method `stub' for nil:NilClass
            from
/opt/local/lib/ruby/gems/1.8/gems/mocha-0.5.6/lib/mocha/object.rb:57:in
`stubs'
            from (irb):3

I found remarkably similar examples online (e.g.,
<http://www.floehopper.org/articles/2007/06/08/mocha-0-5-released>)
which don't work here, either, which puzzled me.  I ran mocha's tests
and they all passed.

So I dug through the source code, and discovered that some setup
methods need to get run before class methods will work, and they get
run automatically as part of unit tests, but not otherwise.

I would suggest some combination of (a) adding to the docs that mocks
only work as advertised inside a TestCase, (b) in object.rb:57, when
$stubba is nil, say something like "you need to run setup_mocha
first!", and/or (c) say in the docs what the setup method is, and how
to run it (maybe it's there, but I didn't see it).

But in any event, this message will soon be in google, so maybe that's enough.


cheers,


- Ken


More information about the mocha-developer mailing list