Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given a parent class Fruit and its subclasses Apple and Banana, is it possible to stub the method foo defined in Fruit, so that any calls to method foo on any instances of Apple and Banana are stubbed?

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

Fruit.any_instance.stubs(:foo) did not work and it looks like it only stubs for instances of Fruit. Is there a simple way to achieve this other than calling stubs for every subclasses?

Found this link raising the similar question but it looks like it has not been answered yet. http://groups.google.com/group/mocha-developer/browse_thread/thread/99981af7c86dad5e

like image 474
Innerpeacer Avatar asked Sep 24 '11 13:09

Innerpeacer


1 Answers

This probably isn't the cleanest solution but it works:

Fruit.subclasses.each{|c| c.any_instance.stubs(:foo)}
like image 122
weexpectedTHIS Avatar answered Oct 23 '22 22:10

weexpectedTHIS