Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 756
Chris Bunch Avatar asked Oct 25 '11 16:10

Chris Bunch


2 Answers

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
like image 52
peakxu Avatar answered Nov 16 '22 00:11

peakxu


or you can use a stubbing framework (like rspec or mocha) and stub the File.Open method.

File.stub(:open => "0\n")

like image 44
Dan Avatar answered Nov 15 '22 22:11

Dan