Test module method with rspec-mocks

385 views
Skip to first unread message

rus...@gmail.com

unread,
Dec 11, 2014, 9:02:48 AM12/11/14
to rs...@googlegroups.com

How to test config method in this module with Rspec 3 mocks?

module TestModule
  class << self
    attr_accessor :config
  end
  def self.config
    @config ||= Config.new
  end
  class Config
    attr_accessor :money_url
    def initialize
      @money_url = "https://example1.come"
    end
  end
end

I tried something like this:

describe "TestModule config" do
  it "should have config instance" do
    config = class_double("TestModule::Config")
    obj = instance_double("TestModule")
    allow(obj).to receive(:config).and_return(config)
    obj.config
    expect(obj.config).to eq(config)
  end
end

It looks, that it doesn't works, why ?

Failures:

1) TestModule config should have config instance Failure/Error: allow(obj).to receive(:config).and_return(config) TestModule does not implement: config # ./spec/config_spec.rb:41:in `block (2 levels) in '


Myron Marston

unread,
Dec 11, 2014, 11:51:38 AM12/11/14
to rs...@googlegroups.com
`config` is a singleton method on `TestModule` (often called a class method when on a module or class).  It's not an instance method.  Change `instance_double("TestModule")` to `class_double("TestDouble")` and it should work.

HTH,
Myron
Reply all
Reply to author
Forward
0 new messages