Stub chain not working
Created by: bradphelan
I have a spec where I do
User.any_instance.stub_chain(:challenges, :won){
[ @challenge1, @challenge2 ]
}
but I get the error
undefined method `playback!' for nil:NilClass
/Users/bradphelan/.rvm/gems/ruby-1.9.2-p180@mysugrapp/gems/activesupport-3.1.0.rc5/lib/active_support/whiny_nil.rb:48:in `method_missing'
/Users/bradphelan/.rvm/gems/ruby-1.9.2-p180@mysugrapp/gems/rspec-mocks-2.6.0/lib/rspec/mocks/any_instance.rb:134:in `playback!'
/Users/bradphelan/.rvm/gems/ruby-1.9.2-p180@mysugrapp/gems/rspec-mocks-2.6.0/lib/rspec/mocks/any_instance.rb:221:in `challenges'
/Users/bradphelan/workspace/mysugr/mysugrapp/app/controllers/challenges_controller.rb:34:in `index_won'
a bit of digging and I modified the code in any_instance to look like
----------------------
/Users/bradphelan/.rvm/gems/ruby-1.9.2-p180@mysugrapp/gems/rspec-mocks-2.6.0/lib/rspec/mocks/any_instance.rb
----------------------
129 def playback!(instance, method_name)
130 RSpec::Mocks::space.add(instance)
131 puts 'BPH'
132 pp @message_chains
133 pp method_name
134 @message_chains[method_name].playback!(instance)
135 @played_methods[method_name] = instance
136 received_expected_message!(method_name) if has_expectation?(method_name)
137 end
The output at this point in the code was
BPH
{"challenges"=>
#<RSpec::Mocks::AnyInstance::StubChain:0x00000106718020
@invocation_order=
{:stub=>[nil],
:with=>[:stub],
:and_return=>[:with, :stub],
:and_raise=>[:with, :stub],
:and_yield=>[:with, :stub]},
@messages=
[[[:stub, "challenges"],
#<Proc:0x00000106718c50@/Users/bradphelan/.rvm/gems/ruby-1.9.2-p180@mysugrapp/gems/rspec-mocks-2.6.0/lib/rspec/mocks/methods.rb:45>]]>}
:challenges
It seems the key in the hash is a string "challenges" but the hash is being indexed by the symbol :challenges and returns null and therefore the crash.
I modified the source code to
def playback!(instance, method_name)
RSpec::Mocks::space.add(instance)
method_name = method_name.to_s
@message_chains[method_name].playback!(instance)
@played_methods[method_name] = instance
received_expected_message!(method_name) if has_expectation?(method_name)
end
and now my spec works