views:

225

answers:

1

I'm using RR for mocking and stubbing in RSpec, and I've run across a situation where I'd like to stub a method from a super class of a controller that sets some instance variables. I can work out how to stub the method call and if I debug I can see that my stubbed block is called, but I cannot get the instance variables in the block to propagate into the class I'm testing.

Just to break it down :

class A < ApplicationController
  before_filter :bogglesnap

  def bogglesnap
    @instancevar = "totally boggled"
  end
end

class B < A
  def do_something_with_instance
    if @instancevar 
      ....
    else
      ....
    end
  end
end

That's the basic setup, and so then in my tests for controller B I'd like to stub out the bogglesnap method from A to set @instancevar to something I want. I just can't figure out how to do it.

I've tried RR's instance_of stubbing and just stubbing out the controller definition :

stub.instance_of(A).bogglensap { @instancevar = "known value" }
stub(controller).bogglesnap { @instancevar = "known value" }

but neither of these seem to work, well, they don't work :)

Does anyone have any pointers on how you should be able to stub that method call out and have it set instance variables? I'm assuming it has to do with the context in which the block is run but am hoping someone has run across something like this before.

Thanks

A: 

You can use instance_variable_set method by calling on the object instance and set it to whatever you want, like so

 controller.instance_variable_set("@instancevar", "known value")

and similarly, if you ever want to fetch the value of an instance variable in your spec or debug or do something else from outside the class then you can get the value by doing

 controller.instance_variable_get("@instancevar")

Mind you, instance_variable_set and instance_variable_get methods are available not only to controllers but all objects as it is provided by ruby. Infact, these two methods play an important role in rails magic :)

nas
I knew of the instance variable and dynamic programming stuff ruby offers, I just hadn't thought of using it... thanks for the brain prod! :)I just tried it and confirmed that it works.
ozzyaaron