[mocha-developer] allow stubbing of previously defined methods such as "id"

Jay jay at jayfields.com
Tue Jan 2 11:44:09 EST 2007


On my current project I needed to create a stub that responded  
correctly to the id message.  Here's the change I put into my copy of  
head.

Index: lib/mocha/mock_methods.rb
===================================================================
--- lib/mocha/mock_methods.rb   (revision 1114)
+++ lib/mocha/mock_methods.rb   (working copy)
@@ -68,6 +68,7 @@
       method_names = method_names.is_a?(Hash) ? method_names :  
{ method_names => nil }
       method_names.each do |method_name, return_value|
         expectations << Stub.new(self, method_name,  
backtrace).returns(return_value)
+        self.metaclass.send :undef_method, method_name if  
self.metaclass.method_defined? method_name
       end
       expectations.last
     end

Index: test/mocha/auto_verify_test.rb
===================================================================
--- test/mocha/auto_verify_test.rb      (revision 1114)
+++ test/mocha/auto_verify_test.rb      (working copy)
@@ -155,6 +155,11 @@
     assert_equal 'named_stub', stub.__mock_name
   end

+  def test_stub_should_respond_to_already_defined_method
+    stub = test_case.stub(:id=>"id")
+    assert_equal "id", stub.id
+  end
+
   def test_should_create_greedy_stub_with_name
     greedy_stub = test_case.stub_everything('named_greedy_stub')
     assert_equal 'named_greedy_stub', greedy_stub.__mock_name



More information about the mocha-developer mailing list