Stub object chains with Mocha

Tagged with mocha Ruby Rails rspec

Language: Ruby

Provides the ability to deep-mock a path of objects.

User.any_instance.stub_path(“projects.all”).returns([])

View as text

require 'mocha'
module Mocha

  module ObjectMethods
    def stub_path(path)
      path = path.split('.') if path.is_a? String
      raise "Invalid Argument" if path.empty?
      part = path.shift
      mock = Mocha::Mockery.instance.named_mock(part)
      exp = self.stubs(part)
      if path.length > 0
        exp.returns(mock)
        return mock.stub_path(path)
      else
        return exp
      end
    end
  end

end
Original snippet written by Unknown
Last updated at 14:38 PM on Jul 07, 2009 by Brian Hogan

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.