4

我正在使用签名的 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 的未定义方法“已签名”

我从thisthis意识到这是在测试用例中以不同方式定义 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
4

1 回答 1

1

您不能像在控制器中那样使用 cookies 变量在测试中设置 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
于 2011-08-16T10:19:58.013 回答