根据标题,我在我的控制器中设置session[:user_id]
如果用户成功通过身份验证,然后测试会话值是否与用户ID匹配,但会话为零,并进行以下设置:
sessions_controlller.rb:
class SessionsController < ApplicationController
def create
user = User.find_by username: params[:username]
if user.try(:authenticate, params[:password])
session[:user_id] = user.id
redirect_to user_posts_path, notice: "Successfully logged in!"
else
redirect_to new_session_path, alert: "Invalid credentials."
end
end
end
session_controller_test.rb:
test "should sign in user with correct credentials" do
user_to_log_in = users(:one)
post :create, { password: "password", username: "yes" }
assert_equal user_to_log_in.id, session[:user_id]
end
user.rb:
class User < ActiveRecord::Base
has_secure_password
end
users.yml里:
one:
id: 1
username: yes
password_digest: <%= BCrypt::Password.create('password', cost: 4) %>
我如何在这里写一个通过测试?
答案 0 :(得分:0)
您可能无需在测试中访问服务器数据,例如会话。查看rack_session_access https://github.com/railsware/rack_session_access以获取可能的答案。
答案 1 :(得分:0)