Sebastian
Sebastian

Reputation: 2204

Setting a session value through RSpec

My current code looks like this:

/spec/support/spec_test_helper.rb

module SpecTestHelper
  def login_admin
    user = FactoryGirl.create(:user, type: 0)
    session[:user_id] = user.id
  end
end

/app/controllers/application_controller.rb

def current_user
  if session[:user_id].nil?
    render plain: 'Error', status: :unauthorized
  else
    @current_user ||= User.find(session[:user_id])
  end
end

Unfortunately, session is always empty in the current_user method. Is there a way of controlling the session through RSpec?

Upvotes: 4

Views: 6634

Answers (1)

Aaron K
Aaron K

Reputation: 6961

This will change based on the spec type. For example, a feature spec will not allow you to directly modify the session. However, a controller spec will.

You will need to include the helper methods module into your example group. Say you have a WidgetsController:

require 'support/spec_test_helper'

RSpec.describe WidgetsController, type: :controller do
  include SpecTestHelper

  context "when not logged in" do
    it "the request is unauthorized" do
      get :index
      expect(response).to have_http_status(:unauthorized)
    end
  end

  context "when logged in" do
    before do
      login_admin
    end

    it "lists the user's widgets" do
      # ...
    end
  end
end

You can also automatically include the module into all specs, or specific specs by using metadata.

I often do this by adding the configuration changes into the file which defines the helper methods:

/spec/support/spec_test_helper.rb

module SpecTestHelper
  def login_admin
    user = FactoryGirl.create(:user, type: 0)
    session[:user_id] = user.id
  end
end

RSpec.configure do |config|
  config.include SpecTestHelper, type: :controller
end

Upvotes: 5

Related Questions