Setting Session Value via RSpec

My current code is as follows:

/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, the session is always empty in the current_user method. Is there a way to control the session through RSpec?

+4
source share
2 answers

This will vary depending on the type of specification. For example, the specification featurewill not allow you to directly modify the session. However, the specification controllerwill be.

You will need to include helper methods in your example group. Let's say you have 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 widgets" do
      # ...
    end
  end
end

specific , metadata.

, , :

/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
+4

:

@request.session[:session_id] = "blabla"
-1

All Articles