Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stub an instance variable inside controller

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)

like image 299
Dty Avatar asked Jan 16 '13 15:01

Dty


2 Answers

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)
like image 167
onetwopunch Avatar answered Sep 23 '22 01:09

onetwopunch


 Bar.any_instance.stub(:can_do_something?)
like image 43
apneadiving Avatar answered Sep 21 '22 01:09

apneadiving