Topic: RSpec: calling original method from within a stub

Hi!

I need to stub a method on a model instance that is going to be fetched by the code I'm speccing. I think I need something like this to implement it:

@original_object = ... #initialization code
@original_object.save!

MyModel.stub!(:find) do |*args|
  obj = yield(*args)
  if obj == @original_object
    obj.stub!(:my_method).and_return ...
  end
  obj
end

Tho I ain't sure what yield does when called inside the block passed to stub! method. Any idea? smile

Or probably something like MyModel.any_instance.stub!(...) (like mocha's any_instance method) would work for me. But as far as I know rspec doesn't have similar functionality, and it is not going to ever appear there...

I'll appreciate any help with that.

Last edited by bluesman.alex (2010-09-16 04:08:36)

Re: RSpec: calling original method from within a stub

Just tried code above and of course it doesn't work, saying 'no block given'

Re: RSpec: calling original method from within a stub

Also tried

MyModel.stub!(:new).and_return @original_object

but somehow find still returns different object (object_id differs). Anybody has an idea, why this happens?

Last edited by bluesman.alex (2010-09-16 04:48:52)

Re: RSpec: calling original method from within a stub

Okay, I have found a solution, however it doesn't look very elegant. smile

$ORIGINAL_OBJ = @original_obj
MyModel.class_eval do
  def self.find(*args)
    obj = super(*args)
    if obj == $ORIGINAL_OBJ
      obj.stub!(:my_method).and_return $ANOTHER_GLOBAL_VARIABLE
    end
    obj
  end
end 

Please let me know if you have an idea how to make it simpler.