I am a Java developer playing with and loving with Ruby. I realized that due to the Ruby metaprogramming capabilities, my unit tests are getting a lot cleaner and I don’t need any unpleasant mocking frameworks. I have a class that needs class services File, and in my test I don’t want to touch my real file system. In Java, I would use some virtual file system for simpler “seams” to skip fake objects, but in Ruby, which are clearly overdone. What I came up with seems to be really pretty compared to the Java world. In my class under testing, I have an optional constructor parameter:
def initialize(file_class=File)
When I need to open files in my class, I can do this:
@file_class.open(filename)
And the call goes either to the real file class, or in the case of my unit test, it goes to a fake class that does not concern the file system. I know there should be a better way to do this with metaprogramming?
source
share