Reputation: 2380
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 ;)
Upvotes: 1
Views: 501
Reputation: 1089
How about this?
allow_any_instance_of(Kernel)
.to receive(:caller)
.and_return(["anything_you_want.rb"])
Upvotes: 1
Reputation: 168269
You are calling caller
from m
. So caller.first
will always be the line that calls m
, which is probably useless. Probably what you wanted is caller[1]
, not caller.first
(or caller[0]
).
Upvotes: 0
Reputation: 66343
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)
Upvotes: 1