Method: Spec::Mocks::Methods#stub_chain

Defined in:
lib/spec/mocks/methods.rb

#stub_chain(*methods) ⇒ Object

:call-seq:

object.stub_chain(:first, :second, :third).and_return(:this)

Supports stubbing a chain of methods. Each argument represents a method name to stub, and each one returns a proxy object that can accept more stubs, until the last, which returns whatever is passed to +and_return_.

Examples

# with this in an example ...
article = double('article')
Article.stub_chain(:authored_by, :published, :recent).and_return([article])
# then this will return an Array with the article double in it:
Article.authored_by(params[:author_id]).published.recent


43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/spec/mocks/methods.rb', line 43

def stub_chain(*methods)
  if methods.length > 1
    if matching_stub = __mock_proxy.find_matching_method_stub(methods[0])
      methods.shift
      matching_stub.invoke_return_block.stub_chain(*methods)
    else
      next_in_chain = Object.new
      stub!(methods.shift) {next_in_chain}
      next_in_chain.stub_chain(*methods)
    end
  else
    stub!(methods.shift)
  end
end