1

我已经定义了一个辅助方法(对于我的 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 是如何做到这一点的——除非我错过了一些重要的步骤——为什么这不起作用?

4

1 回答 1

0

也许我以前没有见过这样设置的辅助方法(我是 Rails 新手),但我见过的辅助方法是在没有控制器的情况下定义的。

通常我会在 helpers 文件夹中看到这样的文件

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

在应用程序控制器中。

对我来说,您似乎将控制器称为辅助方法,我不确定这样做有什么好处 - 但我想我不会。

抱歉,如果这没有帮助

于 2014-04-08T23:17:49.973 回答