Permalink
Browse files

Fix any_instance to handle methods defined on superclasses.

Previously, the recorder implementation created a SystemStackError.

Closes #152.
  • Loading branch information...
1 parent b828604 commit 1272c8a60cd43693416490b96eb5a85cd60b1e20 @daneget daneget committed with myronmarston Aug 2, 2012
Showing with 22 additions and 2 deletions.
  1. +4 −2 lib/rspec/mocks/any_instance/recorder.rb
  2. +18 −0 spec/rspec/mocks/any_instance_spec.rb
@@ -175,7 +175,8 @@ def observe!(method_name)
backup_method!(method_name)
@klass.class_eval(<<-EOM, __FILE__, __LINE__)
def #{method_name}(*args, &blk)
- self.class.__recorder.playback!(self, :#{method_name})
+ klass = self.method(:#{method_name}).owner
+ klass.__recorder.playback!(self, :#{method_name})
self.__send__(:#{method_name}, *args, &blk)
end
EOM
@@ -186,7 +187,8 @@ def mark_invoked!(method_name)
@klass.class_eval(<<-EOM, __FILE__, __LINE__)
def #{method_name}(*args, &blk)
method_name = :#{method_name}
- invoked_instance = self.class.__recorder.instance_that_received(method_name)
+ klass = self.method(:#{method_name}).owner
+ invoked_instance = klass.__recorder.instance_that_received(method_name)
raise RSpec::Mocks::MockExpectationError, "The message '#{method_name}' was received by \#{self.inspect} but has already been received by \#{invoked_instance}"
end
EOM
@@ -827,6 +827,24 @@ class RSpec::SampleRspecTestClass;end
end
end
+ context "when used with base class" do
+ let(:sub_klass) { Class.new(klass) }
+
+ it "should stub method in base class" do
+ klass.any_instance.stub(:existing_method).and_return("foo")
+ sub_klass.new.existing_method.should == "foo"
+ end
+
+ it "fails if the method is invoked on a second instance" do
+ instance_one = sub_klass.new
+ instance_two = sub_klass.new
+ expect do
+ klass.any_instance.should_receive(:existing_method)
+ instance_one.existing_method
+ instance_two.existing_method
+ end.to raise_error(RSpec::Mocks::MockExpectationError, "The message 'existing_method' was received by #{instance_two.inspect} but has already been received by #{instance_one.inspect}")
+ end
+ end
end
end
end

0 comments on commit 1272c8a

Please sign in to comment.