Rails 控制器测试:如何在测试时禁用控制器的 before_filter?
控制器的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@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 doUserSession.create @user
. IMHO, I think your tests will be less brittle and less tied to implementation by doing it the latter way.可能您不应该在过滤器之前禁用。我认为你应该以测试方式登录:
May be you shouldn't disable before filter. I think you should just log in in a testing way: