rspec view stubs and partials
Asked Answered
E

1

4

I'm testing a view with RSpec (2.12 on Rails 3.2.8). I'm using CanCan to conditionally display certain elements on a page. This requires a controller method 'current_user'. In some of my specs I've been able to stub out current_user, eg. controller.stub(:current_user).and_return(etc) or view.stub.etc .

This works for some of my specs. But I've got a couple where it's not working and I don't understand why.

The two specs where it's not working test a view, which calls down into a partial, and inside the partial I access 'current_user' as a method. The error is

undefined local variable or method `current_user' 

So I guess my question is how to stub methods correctly so that they can be accessed down inside partials.

How should it be done?

Electrograph answered 29/12, 2012 at 19:12 Comment(0)
Z
11

A controller stub won't work because you're not testing a controller, you're testing a view. Just use a view stub instead:

view.stub(:current_user).and_return(etc)

This should work in a partial as well as in a view.

See: passing view spec that stubs a helper method

Zeta answered 29/12, 2012 at 20:44 Comment(2)
That was the first thing I tried, but it didn't work, so I tried controller.stub and that didn't work either. So now I'm mystified. I can get view.stub(etc) to work if and only if it's a one level view that's being tested. If the view calls a partial, then the method isn't available in the partial.Electrograph
Ah! I worked it out, I need to have both view.stub(:current_user) and controller.stub(:current_user). Any references to current_user in the view, go through to the view.stub, and any references to current_user inside the CanCan ability class go through to controller.stubElectrograph

© 2022 - 2024 — McMap. All rights reserved.