title: How to write an Rspec controller test with authentication?
body: <p>I have two models:</p>
  
  <pre><code># app/models/user.rb
  class User &lt; ActiveRecord::Base
    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable, :validatable, :confirmable
  
    has_many :teams, dependent: :destroy
  end
  </code></pre>
  
  <p>and</p>
  
  <pre><code># app/models/team.rb
  class Team &lt; ActiveRecord::Base
    belongs_to :user
  
    validates_presence_of :user
  end
  </code></pre>
  
  <p>I am trying to test my <code>TeamsController</code> using <a href="http://rspec.info/" rel="nofollow">Rspec</a> and <a href="https://github.com/thoughtbot/factory_girl_rails" rel="nofollow">factory_girl_rails</a>.</p>
  
  <p>Before I can create a new Team I need an authenticated User.</p>
  
  <p>I created a :user factory:</p>
  
  <pre><code>FactoryGirl.define do
    factory :user do
      first_name   "John"
      last_name    "Doe"
      email        {|n| "email#{n}@email.com" }
      mobile_phone "1235551234"
      company_name "Widgets Inc."
      password     "password"
    end
  end
  </code></pre>
  
  <p>Here are the relevant parts of <code>teams_controller_spec.rb</code>:</p>
  
  <pre><code>require 'rails_helper'
  
  RSpec.describe TeamsController, type: :controller do
  
    # This should return the minimal set of values that should be in the session
    # in order to pass any filters (e.g. authentication) defined in
    # TeamsController. Be sure to keep this updated too.
    let(:valid_session) { {} }
  
    describe "GET #index" do
      it "assigns all teams as @teams" do
        user = FactoryGirl.create(:user)
  
        team = Team.create!(name: "New Team Name", user: user)
  
        get :index, {}, valid_session
        expect(assigns(:teams)).to eq([team])
      end
    end
  end
  </code></pre>
  
  <p>The test is failing:</p>
  
  <pre><code>1) TeamsController GET #index assigns all teams as @teams
       Failure/Error: get :index, {}, valid_session
       NoMethodError:
         undefined method `authenticate' for nil:NilClass
  </code></pre>
  
  <p>I don't understand how I need to populate <code>:valid_session</code> so that the test will pass. I thought I'd have to explicitly call an authenticate method but that might not be true. I'm trying to test the Team controller... not User authentication.</p>
  
  <p>Any advice would be much appreciated.</p>