我使用已签名的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中匹配它的authenticate方法时,我得到NoMethodError:
NoMethodError:{}的未定义方法`signed':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
答案 0 :(得分:1)
您不能像在控制器中那样使用cookies变量在测试中设置cookie。 测试中的cookies变量用于在执行请求调用(获取/发布...)之后读取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