我已经定义了一个辅助方法(对于我的 rails 引擎):
module Xaaron
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
helper_method :current_user
helper_method :authenticate_user!
def current_user
@current_user ||= Xaaron::User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
end
def authenticate_user!
if current_user
true
else
redirect_to xaaron.login_path
false
end
end
protected
def record_not_found
flash[:error] = 'Could not find specified role'
redirect_to xaaron.record_not_found_path
true
end
end
end
据我所知,就创建辅助方法而言,上述一切都是正确的。所以现在我需要使用这个辅助方法:
module Xaaron
class ApiKeysController < ActionController::Base
before_action :authenticate_user!
def index
@api_key = Xaaron::ApiKey.where(:user_id => current_user.id)
end
def create
@api_key = Xaaron::ApiKey.new(:user_id => current_user.id, :api_key => SecureRandom.hex(16))
create_api_key(@api_key)
end
def destroy
Xaaron::ApiKey.find(params[:id]).destroy
flash[:notice] = 'Api Key has been deleted.'
redirect_to xarron.api_keys_path
end
end
end
如您所见,在执行每个操作之前,必须对用户进行身份验证。因此,authenticat_user!
然后调用该方法。
让我们为此编写一个测试
it "should not create an api key for those not logged in" do
post :create
expect(response).to redirect_to xaaron.login_path
end
我们希望这会将我们送回登录路径,因为我们没有登录,并且您会记得我们在 API 控制器中的每个操作之前使用身份验证。相反,我们得到了什么:
1) Xaaron::ApiKeysController#create should not create an api key for those not logged in
Failure/Error: post :create
NoMethodError:
undefined method `authenticate_user!' for #<Xaaron::ApiKeysController:0x007f898e908a98>
# ./spec/controllers/api_keys_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
最后我检查了我定义辅助方法的方式是 rails casts 是如何完成的,其他堆栈问题是如何完成的以及 rails docs 是如何做到这一点的——除非我错过了一些重要的步骤——为什么这不起作用?