我使用签名 cookie 来跨页面维护我的用户,几乎实现为 here .
我使用两种方法,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
最佳答案
您不能像在 Controller 中那样使用 cookie 变量在测试中设置 cookie。
测试中的 cookies 变量用于在执行请求调用(get/post...)后读取 cookie 而不是用于写入
为了在您的测试中欺骗登录,您应该通过@request.cookies[:auth] 设置 cookie
您可以将以下方法放入您的 test_helper 并在您的所有测试中使用它
def signin user
@request.cookies[:auth] = user.auth
end
在你的测试中
test "get dashboard if logged in" do
signin @user
get :index
end
关于unit-testing - 签名 cookie 和测试 :unit don't mix: "NoMethodError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6223280/