stub an instance variable inside controller

10,332

Solution 1

For the record, this is a bit cleaner I think:

bar = Bar.new # or use FactoryGirl to create a Bar factory
bar.stub(:can_do_something?) { # return something }
controller.instance_variable_set(:@bar, bar)

Solution 2

 Bar.any_instance.stub(:can_do_something?)

Solution 3

If all else fails you could do something similar to any_instance.stub. For the record, this makes me feel dirty.

Bar.class_eval do
  alias :original_can_do_something? :can_do_something?

  def can_do_something?  # "stub" method
    # Return whatever you need here
  end
end

# Run your test

Bar.class_eval do
  alias :can_do_something? :original_can_do_something?  # "unstub" the method
end
Share:
10,332
Dty
Author by

Dty

SOreadytohelp

Updated on July 26, 2022

Comments

  • Dty
    Dty almost 2 years

    I'm using rspec 1.3.2 to test a controller action that looks something like this:

    def action_foo
      ...
      @bar.can_do_something?
      ...
    end
    

    I'm trying to stub @bar (assume it's an instance of class Bar) instance variable but am unable to. I think if I had access to any_instance then I could do Bar.any_instance.stub(:can_do_something?) but that's not available in the version of rspec I am using.

    Is there another way to access and stub @bar? None of the following worked:

    @bar.stub(:can_do_something?)
    controller.instance_variable_get("@bar").stub(:can_do_something?)
    controller.stub_chain(:bar, :can_do_something?)
    Bar.new.stub(:can_do_something?)
    

    Edit:

    @bar is assigned in a before_filter. something like @bar = Bar.find(n)

    • Dave Newton
      Dave Newton over 11 years
      Where/how is @bar instantiated?
    • Dty
      Dty over 11 years
      @bar is assigned in a before_filter
  • Dty
    Dty over 11 years
    @bar is assigned in a before_filter
  • apneadiving
    apneadiving over 11 years
    So do: Bar.should_receive(:find).and_return your_object_or_mock
  • Dty
    Dty over 11 years
    i'm not going with this solution but accepting your answer since it's the only one that answered my question
  • jibiel
    jibiel over 9 years
    It's allow_any_instance_of(Bar).to receive(:can_do_something?).and_return true nowadays.