首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在functional Rails测试中为authenticate_user抛出Devise warden错误

在functional Rails测试中为authenticate_user抛出Devise warden错误
EN

Stack Overflow用户
提问于 2012-06-22 16:26:39
回答 4查看 6.6K关注 0票数 7

我有一个资源,其中的新操作需要用户登录才能查看。如果用户试图在未登录的情况下创建新资源,则他们被重定向(302'd)到登录页面。我的功能测试如下所示:

代码语言:javascript
复制
  test "should not get new unless logged in" do
    get :new
    assert_response :redirect
  end

堆栈跟踪如下所示:

代码语言:javascript
复制
ArgumentError: uncaught throw :warden
    /.../gems/warden-1.1.1/lib/warden/proxy.rb:114:in `throw'
    /.../gems/ruby-1.9.2-p318/gems/warden-1.1.1/lib/warden/proxy.rb:114:in `authenticate!'
    /.../gems/ruby-1.9.2-p318/gems/devise-2.0.4/lib/devise/controllers/helpers.rb:48:in `authenticate_user!'

在执行新操作之前,我有一个指向authenticate_user的before_filter。

我理解为什么authenticate_user!失败了,但我不明白为什么它会抛出一个错误。难道它不应该像在webapp中那样表现吗?是否将用户重定向到登录页面?

谢谢。

EN

回答 4

Stack Overflow用户

发布于 2015-04-24 06:34:33

按照documentation说的做:

代码语言:javascript
复制
class ActionController::TestCase
  include Devise::TestHelpers
end

特别是,不要将include Devise::TestHelpers放到class::TestCase中。

票数 5
EN

Stack Overflow用户

发布于 2013-12-22 10:05:31

当Warden和/或Devise in缺失或没有添加到适当的位置时,就会发生这种情况。将它们添加到test_helper.rb中是很有诱惑力的,因为这是助手通常要去的地方,但对于Devise来说,这将不能正常工作。

有关更多详细信息,请参阅https://github.com/plataformatec/devise/issues/1029

为了解决这个问题,在控制器的测试类中包含Devise helper和Warden helper,如下所示:

代码语言:javascript
复制
require 'test_helper'                                  
class UserControllerTest < ActionController::TestCase  
  include Devise::TestHelpers                          
  include Warden::Test::Helpers                        
  Warden.test_mode!                                    

  def teardown                                         
    Warden.test_reset!                                 
  end                                                  

  # test "the truth" do                               
  #   assert true
  # end
end

这对于使用Devise身份验证的每个控制器都是必需的。

编辑:正如在下面的评论中提到的,将include Warden:TestHelpers从spec_helper.rb (或test_helper.rb)移到rails_helper.rb也是可行的。

票数 2
EN

Stack Overflow用户

发布于 2016-07-27 23:46:50

我得到了这个错误,但这是因为我把我的include Devise::TestHelpers放在我的类定义之外。

代码语言:javascript
复制
require 'test_helper'
include Devise::TestHelpers

class Admin::ObservationsControllerTest < ActionController::TestCase
  setup do
  ...

这抛出了我7个测试用例中的3个的典狱长错误。在类定义中移动include可以修复所有问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11152671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档