我试图测试我在项目中实施的身份验证方法。我没有使用Devise或Doorkeeper,而是我在互联网上找到的解决方案。测试注册操作很容易,因为我在数据库中检查用户是否已成功创建。但我不确定如何检查用户是否已成功登录。经过一些研究后,我决定检查用户登录时,会话[:user_id]是否与user.id匹配。在控制台中调试我可以看到它们都匹配,但是当我尝试启动测试时,它返回我的nil并且我不知道为什么。提前谢谢
sessions_controller.rb
class SessionsController < ApplicationController
before_filter :authenticate_user, :only => [:home, :profile, :setting]
before_filter :save_login_state, :only => [:login, :login_attempt]
def login
end
def login_attempt
puts "I get here"
authorized_user = User.authenticate(params[:email],params[:password])
if authorized_user
session[:user_id] = authorized_user.id
flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.username}"
redirect_to(:action => 'profile')
else
flash[:notice] = "Invalid Username or Password"
flash[:color]= "invalid"
render "login"
end
end
def logout
session[:user_id] = nil
redirect_to :action => 'login'
end
def profile
end
end
sessions_spec.rb
require 'rails_helper'
describe 'Login route' do
it "a user logs in with email and password when registered" do
post "/register", {
username: "David",
email: "testingemail@gmail.com",
encrypted_password: "secret101"
}
post "/login_attempt", {
email: "testingemail@gmail.com",
password: "secret101"
}
user_id = User.first.id
puts user_id
expect(session[:user_id]).to eq(user_id)
end
end
这是我得到的结果
失败/错误:期望(会话[:user_id])。到eq(user_id)
expected: BSON::ObjectId('56a7a1b0e389a21fb8f3e07a')
got: nil
答案 0 :(得分:0)
我的问题的解决方案是我无法通过我尝试的方式访问测试中的会话。我需要做这样的事情
session_id = last_request.env['rack.session']['user_id']