Rails 控制器测试:如何在测试时禁用控制器的 before_filter?

发布于 2024-10-21 17:41:32 字数 482 浏览 5 评论 0原文

控制器的 before_filter 期望用户登录。这就是控制器测试失败的原因(如果我从 before_filter 中删除用户身份验证调用,则工作正常)。测试时是否可以禁用用户身份验证调用?

class Company::BranchController < ApplicationController
  before_filter **:require_user**, :only => [:show, :edit, :update, :new, :create, :index]

  def create
    @branch = Company::Branch.new(params[:branch])
    if @branch.save
      redirect_to :action => :index             
    else
      render :action => :new    
    end
  end
end

before_filter of controller expects user to be logged in. this is why test of controller fails(work fine if i remove user authentication call from before_filter). Is it possible if user authentication call can be disabled while testing ?

class Company::BranchController < ApplicationController
  before_filter **:require_user**, :only => [:show, :edit, :update, :new, :create, :index]

  def create
    @branch = Company::Branch.new(params[:branch])
    if @branch.save
      redirect_to :action => :index             
    else
      render :action => :new    
    end
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陪我终i 2024-10-28 17:41:32

@Antiarchitect 是正确的,但是,考虑到您的问题的上下文,我认为您应该考虑模拟用户登录与删除方法检查。

有多种方法可以使用用户/登录包来做到这一点。对于 Devise,它提供了一个简单的 sign_in @user 方法;使用 Authlogic,您可以执行UserSession.create @user。恕我直言,我认为通过后一种方式,您的测试将不那么脆弱,并且与实现的联系也更少。

@Antiarchitect is correct, however, given the context of your problem, I think you should consider simulating having a user signed in vs. stubbing out the method checking.

There are ways to do this with the user/login packages out there. For Devise, it provides a simple sign_in @user method; with Authlogic, you can do UserSession.create @user. IMHO, I think your tests will be less brittle and less tied to implementation by doing it the latter way.

烟雨凡馨 2024-10-28 17:41:32

可能您不应该在过滤器之前禁用。我认为你应该以测试方式登录:

 before(:each) do
   @current_user = Factory.create(:user)
   controller.stubs(:current_user).returns(@current_user)
 end

May be you shouldn't disable before filter. I think you should just log in in a testing way:

 before(:each) do
   @current_user = Factory.create(:user)
   controller.stubs(:current_user).returns(@current_user)
 end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文