Given the Thread class with it current method.
Now inside a test, I want to do this:
def test_alter_current_thread
Thread.current = a_stubbed_method
# do something that involve the work of Thread.current
Thread.current = default_thread_current
end
Basically, I want to alter the method of a class inside a test method and recover it after that.
I know it sound complex for another language, like Java & C# (in Java, only powerful mock framework can do it). But it’s ruby and I hope such nasty stuff would be available
You might want to take a look at a Ruby mocking framework like Mocha, but in terms of using plain Ruby it can be done using
alias_method(documentation here) e.g.beforehand:
then define your new method
then afterwards restore the old method:
Update to illustrate doing this from within a test
If you want to do this from within a test you could define some helper methods as follows:
replace_class_methodis expecting a class constant, the name of a class method and the new method definition as a string.restore_class_methodtakes the class and the method name and then aliases the original method back in place.Your test would then be along the lines of:
You could also write a little wrapper method which would replace a method, yield to a block and then ensure that the original method was reinstated afterwards e.g.
Inside your test method this could then be used as:
As mentioned in the original answer, you can probably find a framework to do this for you but hopefully the above code is interesting and useful anyway.