Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

stub

rspec

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.

like image 303
Pedro Avatar asked Nov 25 '08 03:11

Pedro


1 Answers

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.

like image 153
Orion Edwards Avatar answered Sep 17 '22 19:09

Orion Edwards