How to test a Ruby module?
Ruby module can be used to group methods and constants together. This tutorial illustrates testing of ruby module either in isolation or based on the class where it is included or extended.
Testing module / self methods
Let’s take a simple example of a Ruby module which contains self (module) methods.
module MyModule
def self.hello
puts "Hello"
end
end
Now, testing of such a module can be done in isolation by calling the class method directly from module.
Below is the rspec test code for the above module.
require 'spec_helper'
RSpec.describe MyModule do
it "should say hello" do
expect(MyModule.hello).to eq("Hello")
end
end
Testing instance methods
Now, let’s take a look at the same example with a class which includes the module to test instance methods on a module.
module MyCalendar
def number_of_months
12
end
end
Now, to test this module, we shall include this module in a dummy class. Then, we test the behaviour of the module method by calling the method on an object of the dummy class.
require 'spec_helper'
class DummyCalendar
include MyCalendar
end
RSpec.describe MyModule do
it "should say number of months" do
calendar = DummyCalendar.new
expect(calendar.number_of_months).to eq(12)
end
end
This will test the module method based on a dummy class. In this way, we don’t need to test the behavior of all the classes where this module is included.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox
