Ruby: make a dummy class (for testing purposes) from a module

Post date: Jan 20, 2014 2:49:24 AM

I'm not ashamed to admit Ruby messes with my head. I'm pretty much an ice-cold master of C, Java, and (mostly) C#, but I feel I've only scratched the surface of Ruby.

So my trick of the day comes from trying to think up a way to unit test a Ruby module with non-module methods, meaning it has to be mixed-into a class before those methods can be called and tested. My first pass was simply to write a throw-away Ruby class that mixed-in the module. But then I though, why not make a function that works for any module?

So I actually wrote two functions:

  1. one that creates a custom class from the module, basically a "class-ified" module
  2. one that creates an object of that class

Here's the code for the first one. All it does is create the new Class object, passing as its body an include statement for the module.

def dummy_class_from mod
    Class.new { include mod }
end

And the second, which simply calls new on the class created from the previous function:

def dummy_instance_of mod
    dummy_class_from(mod).new
end