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.
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
or you can use a stubbing framework (like rspec or mocha) and stub the File.Open method.
File.stub(:open => "0\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With