我正在使用签名的 cookie 来跨页面维护我的用户,几乎像这里一样实现。
我使用两种方法,sign_in(account) 和 sign_out 来操作我的 cookie,按照您的期望创建或销毁它们......
module SessionsHelper
def sign_in account
cookies.signed[:auth_account] = {
:expires => 1.week.from_now,
:value => [account.id, account.hash]
}
end
def sign_out
cookies.delete(:auth_account)
end
end
但是,当尝试使用此方法或功能测试中在 ApplicationController 中与之匹配的身份验证方法时,我得到一个 NoMethodError:
NoMethodError: {}:ActiveSupport::HashWithIndifferentAccess 的未定义方法“已签名”
我从this和this意识到这是在测试用例中以不同方式定义 cookie 的问题,但我无法让这些解决方案中的任何一个起作用。为了完整起见,示例测试因上述错误而失败:
require 'test_helper'
class AccountsControllerTest < ActionController::TestCase
include SessionsHelper
setup do
# We need to fake authentication by manually
# assigning an account to the sign_in process
sign_in accounts(:ia)
@account = accounts(:ia)
end
test "should 403 on index if unauthenticated" do
sign_out
get :index
assert_response :forbidden
end
test "should 200 on index if authenticated" do
get :index
assert_response :success
end
end