Rails - Rspec - Testing Your Modules


Programming in Ruby tutorials and examples

Rails - Rspec - Testing Your Modules


I have been working on a project recently where modules are used extensively to share behaviour between model classes. I was looking to use an example from the system but they were all overly complex and detracted from the subject - testing modules. So in the following contrived example I will show you how to test the behavior of a module using rspec. The following “Pointless” module adds a class method which will scramble a class name…. doesn’t get more pointless than that!

1
2
3
4
5
6
7
8
9
module Pointless
  extend ActiveSupport::Concern

  module ClassMethods
    def scrambled_class_name
      Digest::MD5.hexdigest(name)
    end
  end
end

Below the module is mixed into two active record classes.

1
2
3
class Post < ActiveRecord::Base
  include Pointless
end
1
2
3
class Comment < ActiveRecord::Base
  include Pointless
end

When testing modules I tend to add a folder under the spec directory called modules. I then use the shared_examples_for group and define specs within the block. When calling described_class it returns the class that the module has been mixed into within the current it_behaves_like context.

spec/modules/pointles_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'spec_helper'

shared_examples_for Pointless do
  context "class methods" do
    it 'should be able to scramble the class name using md5' do
      described_class.scrambled_class_name.should == Digest::MD5.hexdigest(described_class.name)
    end
  end
end

describe Post do
  it_behaves_like Pointless
end

describe Comment do
  it_behaves_like Pointless
end

It’s then just a matter of using describe for each class the module has been mixed into and call it_behaves_like Module, then the specs for the module will be run in the context of the class.

Comments