[rspec-users] Stubbing before_filters with RSpec and stub!

Joseph DelCioppio joseph.delcioppio at gmail.com
Thu Jun 10 22:07:39 EDT 2010


Guys,

I've got a private controller method which acts as a before_filter
that I'm trying to stub.

class TasksController < ApplicationController
  before_filter :load_user

 ......

  private

  def load_user
    if current_user.id == params[:user_id].to_i
     @user = current_user
    else
      flash[:notice] = "Sorry but you can't view other people's
tasks."
      redirect_to root_path
    end
  end
end


describe TasksController do

  before(:each) do
    @user = Factory(:user)
    sign_in @user
    @task = Factory(:task)
    User.stub_chain(:where, :first).and_return(@user)
    controller.stub!(:load_user).and_return(@user)
  end

.......
end

However, even though I'm stubbing load_user, the actual function is
still being called, because I can make all my tests either pass/fail
if I simply have load_user neglect to return @user.

If I have stubbed load_user, should it just always return @user, no
matter what I do to the actual controller method?  I thought that this
was the point of stubbing, that way if I change load_user in the
future, only the tests specifically designed to exercise load_user
will fail, but the rest of my suite will still pass.

I'm going to post my entire controller and spec and provide the Gist
links in case the abbreviated versions I gave aren't enough.

http://gist.github.com/433942

Thanks in advance,

Joe


More information about the rspec-users mailing list