4

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?

5
  • for feature spec or controller specs? Commented May 26, 2015 at 15:11
  • how/where do you call login_admin ? Commented May 26, 2015 at 15:20
  • in banners_controller_spec, in an it "..." do block Commented May 26, 2015 at 15:34
  • 1
    weird you dont have to do anything else then. (github.com/rails/rails/blob/…) Commented May 26, 2015 at 15:39
  • Could it be that I'm doing the check in a before_action filter? Commented May 26, 2015 at 15:46

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

I had the same issue and it didn't help me, I am getting the same error. "undefined local variable or method `session' for #<RSpec::ExampleGroups:"
You should include require 'rails_helper' to the SpecTestHelper

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.