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
Comments
-
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 classBar
) instance variable but am unable to. I think if I had access toany_instance
then I could doBar.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 abefore_filter
. something like@bar = Bar.find(n)
-
Dave Newton over 11 yearsWhere/how is
@bar
instantiated? -
Dty over 11 years
@bar
is assigned in abefore_filter
-
-
Dty over 11 years
@bar
is assigned in abefore_filter
-
apneadiving over 11 yearsSo do:
Bar.should_receive(:find).and_return your_object_or_mock
-
Dty over 11 yearsi'm not going with this solution but accepting your answer since it's the only one that answered my question
-
jibiel over 9 yearsIt's
allow_any_instance_of(Bar).to receive(:can_do_something?).and_return true
nowadays.