Use modules for testing
An approach to mocking behavior can be using modules to mock interactions
There are certain cases when you are unit testing that you need to isolate behavior of an object interaction. Modules can become an important role in testing for just this type of isolation. To understand how this works, you’ll have to know how ruby deals with the call stack of an object. The last definition of a method of an object wins.
For instance, say you have a class:
class World
def hello
"world"
end
end
world = World.new
world.hello
# results: "world"
Now if you extend a module, you can override method definitions of the object.
For instance,
module Planet
def hello
"planet"
end
end
world = World.new
world.extend Planet
world.hello
# results: "planet"
In the above example, the module method hello
is called because we extend the instance class of World
with the module Planet
. This only overrides the module method for the particular instance of World
and not the the actual World
class.
Now as far as testing, say you need to isolate a particular expected collection to change a serializer. You can create a module that returns the mocked collection and extend the object instance you are testing against to return the collection.
Who needs a mock lib after all.