Reputation: 1051
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?
Upvotes: 4
Views: 2462
Reputation: 802
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
Upvotes: 0
Reputation: 42789
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
Upvotes: 5