4

With rails 4.2.0 and the latest version of RSpec I generated a controller test.

How would I ensure my admin user is logged in?

For example: if current_user.admin?

In the rspec test it mentions it like so:

let(:valid_session) { {} }

How would I enter a valid session?

2 Answers 2

5

First you need to add the devise helpers in spec_helper file to be accessible in the tests, as mentioned in the wiki

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

Then in the controller you could easily create a user object and sign it in using sign_in helper method

Sign up to request clarification or add additional context in comments.

2 Comments

Or include Devise::Test::ControllerHelpers for Devise >= 4.1.1 as is now mentioned in the same wiki.
The mentioned wiki moved here for Devise >= 4.2.0.
0

Step 1: You can create custom methods like following in spec folder and then simply use them (after you have done what @Mohammad AbuShady's answer states which usually is done by default in rspec)

module ControllerMacros
  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in FactoryBot.create(:user, admin:true)
    end
  end

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      sign_in FactoryBot.create(:user)
    end
  end
end

Step 2:

Add login_user or login_admin to your spec file wherever you need and change

let(:valid_session) { {} }

to

let(:valid_session) { {"warden.user.user.key" => session["warden.user.user.key"]} }

I hope you are using devise and warden which are really useful if you don't want to worry about session/login/signup issues.

You can see their documentations here: plataformatec/devise wardencommunity/warden

This answer was written based on documentation of devise: devise-wiki-how-to-test

Comments

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.