Using Rspec to test Ruby Modules Supporting tagline
Ruby modules are used to group together methods, classes and contants. Ruby Docs
Here’s an example Module
module MyLovelyModule
def my_lovely_method
save_world
end
end
This module attempts to save the world. No doubt a huge undertaking and needless to say, it needs to be thoroughly tested! A Module cannot be unit tested in the same way as you’d test a class, in the sense that you cannot instantiate a Module. This is by design as Modules are meant to be mixed into classes. So if you want to test this module in isolation you can create a dummy class, include this module in that dummy class and thus test its functionality.
Here’s an example using Rspec.
describe MyLovelyModule do
class DummyClass
end
before(:all) do
@dummy = DummyClass.new
@dummy.extend MyLovelyModule
end
describe "my_lovely_method" do
it "saves the world" do
expect {
@dummy.my_lovely_method
}.to raise_error MeltDownException
end
end
end
So within the describe block we create the dummy class. It doesn’t do much, but in the before hook it extends the MyLovelyModule module and gets it’s functionality mixed in. And so we can use that dummy class to spec the modules functionality.