Pedro Pedro - 4 months ago 10
Ruby Question

rspec: How to stub an instance method called by constructor?

class A
def initialize
@x = do_something
end

def do_something
42
end
end


How can I stub
do_something
in rspec, before the original implementation is called (thus assigning 42 to
@x
)? And without changing the implementation, of course.

Answer

Here's the commit which adds the feature to rspec - This was on May 25 2008. With this you can do

A.any_instance.stub(do_something: 23)

However, the latest gem version of rspec (1.1.11, October 2008) doesn't have this patch in it.

This ticket states that they yanked it out for maintenance reasons, and an alternative solution hasn't yet been provided.

Doesn't look like you can do it at this point. You'll have to hack the class manually using alias_method or somesuch.