rubyruby-mocha

Mocha: Why can't I stub #caller method?


using Mocha in simple code turned in unexpected way. Could you explain what is going wrong?

require 'test-unit'
require 'mocha'

class A
  def m
    caller.first
  end
end

So using this simple class, we can get the latest caller:

A.new.m #=> "(irb):32:in `irb_binding'" (for example)

But if I want to stub caller call, things going wrong.

a = A.new
a.stubs(:caller)

Mocha::ExpectationError: unexpected invocation: #<A:0x6aac20>.caller()

My guess is to check out Mocha sources, but I will do it later ;)



Solution

  • This is a partial explanation, but I hope it is still useful.

    As you've suggested, a way to understand what's going on here is to check the Mocha sources. I think the key to the issue is that the Expectation class, which is used when creating the stub, makes use of the caller method itself.

    A workaround would be to use alias_method e.g.

    class A
      alias_method :my_caller, :caller # allow caller to be stubbed
    
      def m
        my_caller.first
      end
    end
    
    a = A.new
    a.stubs(:my_caller)