Search code examples
rubytestingmonkeypatchingrcov

Un-monkey patching a class/method in Ruby


I'm trying to unit test a piece of code that I've written in Ruby that calls File.open. To mock it out, I monkeypatched File.open to the following:

class File
  def self.open(name, &block)
    if name.include?("retval")
      return "0\n"
    else
      return "1\n"
    end
  end
end

The problem is that I'm using rcov to run this whole thing since it uses File.open to write code coverage information, it gets the monkeypatched version instead of the real one. How can I un-monkeypatch this method to revert it to it's original method? I've tried messing around with alias, but to no avail so far.


Solution

  • Expanding on @Tilo's answer, use alias again to undo the monkey patching.

    Example:

    # Original definition
    class Foo
      def one()
        1
      end
    end
    
    foo = Foo.new
    foo.one
    
    # Monkey patch to 2
    class Foo
      alias old_one one
      def one()
        2
      end
    end
    
    foo.one
    
    # Revert monkey patch
    class Foo
      alias one old_one
    end
    
    foo.one