我正在尝试在rspec中设置控制器的存根身份验证。当我存根authorize方法时,无论我提供什么值,测试都会通过。
控制器:
class FoosController < ApplicationController
before_filter :authorize
...
endApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
protected
def authorize
return true if current_user
flash[:error] = 'Please login'
redirect_to signin_path
false
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end规格:
# this passes (expected)
it "..." do
controller.stubs(:current_user).returns(User.new)
get :index
response.should be_success
end
# this fails (expected)
it "..." do
controller.stubs(:current_user).returns(nil)
get :index
response.should be_success
end
# this passes (expected)
it "..." do
controller.stubs(:authorize).returns(true)
get :index
response.should be_success
end
# Problem: this passes (unexpected)
it "..." do
controller.stubs(:authorize).returns(false)
get :index
response.should be_success
end似乎只要我使用stub :authorize,无论设置什么值,它都会传递before_filter。我认为这可能是受保护的/helper_method名称,但使用这些名称并没有改变任何事情。
为什么存根:authorize with false会导致before_filter通过?
发布于 2011-09-11 09:02:04
我认为您需要检查正在呈现的内容。
看看你的代码,如果当authorize返回false时调用链确实停止了,那么会发生什么呢?
没有重定向或渲染调用。
所以这将是一个空洞的回应?
空的回答仍然是200分。
但是,根据您使用的Rails版本,在Rails3.1中,返回false的before_filter不再停止链是可能的。
实际上,想要停止链的before_filter应该执行以下操作之一
发布于 2013-07-15 05:25:17
我会回答你的最后一个问题Why does stubbing :authorize with false cause the before_filter to pass?
您使用的是存根方法authorize,它会停止调用其中的所有代码,但会返回与存根一起显式返回的内容。
它工作正常,因为当您将current_user存根到false时,authorize将被完全调用。我认为你的最后测试实际上并没有为你测试任何东西,但这只是我的观点。
https://stackoverflow.com/questions/7375333
复制相似问题