Les Hill github twitter facebook linked in archives
Posted August 05, 2009

Thanks to Josh Nichols for pointing out that the original code (and the RSpec mock code!) did not handle stubbing the same part of the chain multiple times, for example:

stub_chain(:votes, :supporting, :count).returns(supporting_count)
stub_chain(:votes, :opposing, :count).returns(opposing_count)

Here is the updated snippet that works when you stub the same part of the chain multiple times:

 1 module StubChainMocha
 2   module Object
 3     def stub_chain(*methods)
 4       if methods.length > 1
 5         next_in_chain = ::Object.new
 6         stubs(methods.shift).returns(next_in_chain)
 7         next_in_chain.stub_chain(*methods)
 8       else
 9         stubs(methods.shift)
10       end
11     end
12   end
13 end
14 
15 Object.send(:include, StubChainMocha::Object)

Copy that into spec/stub_chain_mocha.rb and then require it from spec_helper.rb.

blog comments powered by Disqus

Thanks to Tom Preston-Werner for the CSS layout, Webby for the blog renderer, and GitHub Pages for the blog hosting.