Is it possible to stub a method in the parent class so that all instances of the subclass are stub in rspec?

Given the parent class Fruit and its subclasses Apple and Banana , is it possible to drown out the foo method defined in Fruit , so that any calls to the foo method on any instances of Apple and Banana hatched?

 class Fruit def foo puts "some magic in Fruit" end end class Banana < Fruit ... end class Apple < Fruit ... end 

Fruit.any_instance.stubs(:foo) didn't work, and it looks like these are just stubs for Fruit instances. Is there an easy way to achieve this other than calling stubs for each subclass?

Found this link by raising a similar question, but it looks like he hasn't answered yet. http://groups.google.com/group/mocha-developer/browse_thread/thread/99981af7c86dad5e

+7
source share
3 answers

This is probably not the cleanest solution, but it works:

 Fruit.subclasses.each{|c| c.any_instance.stubs(:foo)} 
+9
source

If your subclasses have subclasses, you may need to recurs them. I did something like this:

 def stub_subclasses(clazz) clazz.any_instance.stubs(:foo).returns(false) clazz.subclasses.each do |c| stub_subclasses(c) end end stub_subclasses(Fruit) 
0
source

UPDATING @weexpectedTHIS answer for Rspec 3.6:

  Fruit.subclasses.each do |klass| allow_any_instance_of(klass).to receive(:foo).and_return(<return_value>) end 
0
source

All Articles