Rspec'ing Rails Views

Posted on February 12, 2007

I've been using rspec for testing rails apps for about a month now. However, I hadn't tried to spec out the views. I decided to starting specing out the views today, and ran into a small obstacle.

I am currently using restful authentication plugin and I have snippets in my view like:


    <% if logged_in? %>
         ....
    <% end %>

Everything is good, until I tried to write my first view test. Calling:

render "controller/template"

I received a missing method error on "logged_in?". The problem is that rspec views are tested in isolation from the controller. This means my include AuthenticatedSystem in the application controller doesn't get loaded and that's where the "logged_in?" method is mixed in.

I did find out that the application_helper.rb and <controller>_helper.rb (where <controller> is the current controller associated with the template being tested) get loaded, so I could define the "logged_in?" method in either of the two helper classes. But the problem with that is that I would have "logged_in?" defined in a couple of places just to run my rspecs.

Digging around in the rspec for rails code base, I found that you can get access to the controller via @controller and the template via @controller.template.

Then a light came on! I could stub out the call to logged_in? on the template like so:

   @controller.template.stub!(:logged_in?).and_return(true)

After doing that, everything worked fine. I also found it came in handy for stubbing out other template calls.

Comments
  1. rickFebruary 12, 2007 @ 09:39 PM
    WJW
  2. Brandon KeepersFebruary 12, 2007 @ 10:34 PM
    Thanks for the tip. I thought I had tried that and it didn't work, but I must have typoed something.
  3. Graeme NelsonFebruary 12, 2007 @ 11:55 PM
    Glad I could help Brandon.