【问题标题】:Signed cookies and Test:unit don't mix: "NoMethodError"签名的 cookie 和测试:单元不混合:“NoMethodError”
【发布时间】:2011-08-16 18:19:58
【问题描述】:

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

我从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

【问题讨论】:

  • 另外,作为旁注,使用 cookies.permanent 时也会出现此错误。我通过手动设置过期时间来解决这个问题,但这是同样的问题。

标签: unit-testing cookies ruby-on-rails-3.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

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2014-03-14
    • 1970-01-01
    • 2013-03-06
    • 2021-01-22
    • 2023-03-31
    相关资源
    最近更新 更多