我已经定义了一个辅助方法(对于我的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如何做到这一点 - 除非我错过了一些主要步骤 - 为什么这不起作用?
答案 0 :(得分:0)
也许我之前没有看过像这样设置的辅助方法(我是rails的新手)但是我看到的辅助方法是在没有控制器的情况下定义的。
通常我会在帮助文件夹
中看到这样的文件module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def current_user=(user)
@current_user = user
end
...
然后
include SessionsHelper
在应用程序控制器中。
对我来说,看起来你正在给控制器调用辅助方法,我不确定这会带来什么好处 - 但我想我不会。
对不起,如果这没用“