Pedro Pedro - 1 year ago 43
Ruby Question

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

class A
def initialize
@x = do_something

def do_something

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

Answer Source

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.