[rspec-users] How do I test my Module?

Ben Mabey ben at benmabey.com
Tue Sep 21 09:58:17 EDT 2010


  On 9/21/10 6:51 AM, Gene Angelo wrote:
> I think I understand basic Class testing, however, how do I test a
> Module's behavior especially (in my case) where the Module will be used
> as an extension primarily e.g. object.extend MyModule.
One option is to extend an object in your spec like so:

describe MyModule do
  subject { Object.new.extend(MyModule) }
  describe "#foo" do
   it "does blah" do
     subject.foo.should == "stuff"
   end
  end
end

I often times will use an OpenStuct to help test modules because they 
allow you to easily set the state.  For example:

module MyModule
   def double
     num * 2
   end
end

require 'ostruct'
describe MyModule do
   def new_object(hash)
     OpenStruct.new(hash).extend(MyModule)
   end
   describe "#double" do
     it "doubles the num var" do
       new_object(:num => 2).double.should == 4
     end
   end
end

HTH,
Ben





More information about the rspec-users mailing list