Strange Stubbing Behaviour

8 views
Skip to first unread message

Rob Percival

unread,
Jan 4, 2012, 11:46:34 AM1/4/12
to mocha-developer
Hi,
I've run into a confusing case where stubbing a method on a parent
class, then calling it via a child class, results in an attempt to
call it on the child class rather than the parent. A simple example
follows. The commented code is a simple monkey patch alternative that
works as expected, whereas the Mocha stubbing does not. Is this a bug
or is it supposed to work this way?

Expected Output:
Child
Parent
not bar

Actual Output:
Child
Parent
<ExpectationError raised>

Example:
require 'rubygems'
require 'mocha'

class Parent
def self.foo()
puts "Parent"
puts bar
end

def self.bar()
"bar"
end
end

class Child < Parent
def self.foo()
puts "Child"
super
end
end

#class Parent
# def self.bar
# "not bar"
# end
#end

Parent.stubs(:bar).returns("not bar")

Child.foo

James Mead

unread,
Jan 4, 2012, 3:58:17 PM1/4/12
to mocha-d...@googlegroups.com
Hi Rob,

Thanks for your email. I'm assuming you are seeing an "unexpected invocation" ExpectationError - is that correct?

I think there is a bug in mocha which I recently described [1] in this (unrelated) Github issue. I'm not sure my initial diagnosis (in that issue comment) was correct, but certainly the behaviour seems undesirable and I think is very closely related to the problem you are describing.

I'm pretty short of time to investigate this at the moment, but it would help if you could add a Github issue to report the problem and then we can keep track of progress in fixing it.

In the short term, while it may not be representative of the way the methods are actually invoked, you might be able to work around the problem by stubbing the method on the Child class instead.

Thanks, James.
----

Reply all
Reply to author
Forward
0 new messages