[rspec-users] modules and stub

David Chelimsky
Mon, 25 May 2009 03:52:38 -0000

On Sun, May 24, 2009 at 7:15 PM, Sarah Allen <lists at ruby-forum.com>
wrote:
> If there is a method defined on a module, how do I stub it?
>
> Imagine I have a module like this:
>
> Module Foo
> ? Module Bar
>
> ? ?def self.do_something(path)
> ?...
> ? ?end
>
>
> ? end
> end
>
>
> Somewhere in the code, there is this call:
> ? ? ? ? ? ? ? Foo::Bar::do_something(path)
>
> In my test I want the above call to do nothing, so I tried this:
> ? ?before(:each) do
> ? ? ?Foo::Bar.stub!(:do_something).and_return
> ? ?end
>
> but I confirm that do_something is getting called by adding a puts in
> it. Do I not have the module/stub syntax correct? ?How can I isolate
> this further?
>
> I tried looking at the doc ( http://rspec.rubyforge.org/rspec/1.2.6/ )
> but I couldn''t really make sense of it.

Stub methods on objects, not modules. The method can be one that
*comes from* a module, but you need to stub it on the specific object
that is at play in the example.

module Foo
  def do_something
end

class Bar
  include Foo
end

describe Bar do
  before(:each) do
    @bar = Bar.new
    @bar.stub(:do_something)
  end
  ...
end

HTH,
David

>
> Thanks,