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

Rob Sanheim rsanheim at gmail.com
Sat Feb 3 17:28:59 EST 2007


On 1/3/07, James Mead <jamesmead44 at gmail.com> wrote:
> On 02/01/07, Jay <jay at jayfields.com> wrote:
>
> > 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
>
> Thanks for the patch. This has been on the todo list for quite some time.
>
> Your solution works fine for some methods (e.g . id), but not for methods
> that Mocha currently relies on (e.g. inspect).
>
> I have been working on a more generic solution which I hope to commit
> shortly.
>

Did anything for this ever get committed?  I'm having issues stubbing
"id" in an ActiveRecord instance.

Code:
  def test_should_use_post_host_for_post_url_when_passed_post_id_only
    post = Post.new
    post.stubs(:id).returns(5)
    post.stubs(:host).returns("internet.seekingalpha.com")
    post_url(:id => post.id).should ==
"http://internet.seekingalpha.com/article/5"
  end

Error:

  1) Error:
test_should_use_post_host_for_post_url_when_passed_post_id_only(LinkSystemTest):
NoMethodError: private method `id' called for #<Mocha::Stub:0x569b224>
    ./test/functional/link_system_test.rb:33:in
`test_should_use_post_host_for_post_url_when_passed_post_id_only'

- Rob


More information about the mocha-developer mailing list