How do I stub part of my session to simulate an authorized session?

rspec, ruby-on-rails-3, ruby-on-rails-3.2, stub

Solution

Considering you are testing the controller, and trying to keep it focussed on the controller you could stub the `current_user` method with a real user or a mock.

before(:each) do
   ApplicationController.any_instance.stub(:current_user).and_return(@user = mock('user'))
end

With that you will have access to the `user` mock to apply further expectations and stubs if needed. If the mock gets in the way, change it out for a real `User` object.

Problem

I have a before filter on my Products Controller: ``` before_filter :authorize, only: [:create, :edit, :update] ``` my `authorize` method is defined in my `application_controller` as: ``` def authorize redirect_to login_url, alert: "Not authorized" if current_user.nil? end ``` and current_user is defined as: ``` def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end ``` In my rspec, I am trying: ``` before(:each) do session.stub!(:user_id).and_return("admin@email.com") end ``` But I am still getting an error as follows: ``` ProductsController PUT update with valid params redirects to the product Failure/Error: response.should redirect_to(product) Expected response to be a redirect to <http://test.host/products/1> but was a redirect to <http://test.host/login> ``` . . . which means that my test is not logged in at the time of the request. What am I missing here? Is there a better way to approach this situation?

Original source