title: Stubbing authentication in request spec
body: <p>When writing a request spec, how do you set sessions and/or stub controller methods?
  I'm trying to stub out authentication in my integration tests - rspec/requests</p>
  
  <p>Here's an example of a test</p>
  
  <pre><code>require File.dirname(__FILE__) + '/../spec_helper'
  require File.dirname(__FILE__) + '/authentication_helpers'
  
  
  describe "Messages" do
    include AuthenticationHelpers
  
    describe "GET admin/messages" do
      before(:each) do
        @current_user = Factory :super_admin
        login(@current_user)
      end
  
      it "displays received messages" do
        sender = Factory :jonas
        direct_message = Message.new(:sender_id =&gt; sender.id, :subject =&gt; "Message system.", :content =&gt; "content", :receiver_ids =&gt; [@current_user.id])
        direct_message.save
        get admin_messages_path
        response.body.should include(direct_message.subject) 
      end
    end
  end
  </code></pre>
  
  <p>The helper: </p>
  
  <pre><code>module AuthenticationHelpers
    def login(user)
      session[:user_id] = user.id # session is nil
      #controller.stub!(:current_user).and_return(user) # controller is nil
    end
  end
  </code></pre>
  
  <p>And the ApplicationController that handles authentication:</p>
  
  <pre><code>class ApplicationController &lt; ActionController::Base
    protect_from_forgery
  
    helper_method :current_user
    helper_method :logged_in?
  
    protected
  
    def current_user  
      @current_user ||= User.find(session[:user_id]) if session[:user_id]  
    end
  
    def logged_in?
      !current_user.nil?
    end
  end
  </code></pre>
  
  <p>Why is it not possible to access these resources?</p>
  
  <pre><code>1) Messages GET admin/messages displays received messages
       Failure/Error: login(@current_user)
       NoMethodError:
         undefined method `session' for nil:NilClass
       # ./spec/requests/authentication_helpers.rb:3:in `login'
       # ./spec/requests/message_spec.rb:15:in `block (3 levels) in &lt;top (required)&gt;'
  </code></pre>