Bugs: Browse | Submit New | Admin

[#18914] Classes that override '==' are likely to experience mocking 'failures' (where the original method is called instead of the mocked method)

Date:
2008-03-18 15:46
Priority:
3
Submitted By:
Nobody
Assigned To:
Nobody (None)
Category:
None
State:
Closed
Summary:
Classes that override '==' are likely to experience mocking 'failures' (where the original method is called instead of the mocked method)

Detailed description
	The problem I have is exhibited by the following test:
---------
require "test/unit"
require 'rubygems'
require 'mocha'

class ExistingClass
  def my_method; true; end
  def ==(o); true; end
end


class MochaTest < Test::Unit::TestCase
  def test_mocha
    2.times do
      obj = ExistingClass.new()
      obj.expects(:my_method).returns(false).at_least_once
      assert_equal(false, obj.my_method)
    end
  end
end
-------------
	Note that if the '2.times' is replaced with '1.times', the test passes, which helps illustrate the bizarreness that
is going on! It is only failing on the second iteration. I believe the cause to be the following method from
Mocha::ClassMethod:

    def eql?(other)
      return false unless (other.class == self.class)
      (stubbee == other.stubbee) and (method == other.method)
    end

	If I add the following patch to my test, it passes:

module Mocha
  class ClassMethod
    def eql?(other)
      return false unless (other.class == self.class)
      (stubbee.object_id == other.stubbee.object_id) and (method == other.method)
    end
    alias_method :==, :eql?
  end
end

	Then the == method can be overridden at will in mocked classes. I'm not sure of the pros/cons of comparing object_ids
like this, or using the 'equal?' method, but I think either would be an improvement over '=='.

	I'm a bit of a ruby noobie, so I hope I'm not getting anything horribly wrong here. Hope this is helpful, and another
great big thank you for your efforts on mocha - it's a great framework, with heaps of potential. Kind regards,

		Andy

Add A Comment: Notepad

Please login


Followup

Message
Date: 2008-03-18 22:39
Sender: James Mead

Fixed in revision 296. I'm closing this bug - please re-open
if it isn't fixed for you. Thanks again for the thorough bug
report.

Cheers, James.
http://blog.floehopper.org

Attached Files:

Name Description Download
No Files Currently Attached

Changes:

Field Old Value Date By
status_idOpen2008-03-18 22:39jamesmead
close_date2008-03-18 22:392008-03-18 22:39jamesmead