rails中的命名错误 - 创建API控制器

时间:2013-12-09 04:04:58

标签: ruby-on-rails ruby rspec

我在app/controllers下设置了我的目录:api/v1/sessions_controller.rb然后我有一个BaseControllerapi/v1/base_controller.rb

然后我将每个类设置为这样:

module Api
  module V1
    class BaseController < ApplicationController
      respond_to :json
      before_action :default_json

      protected

      def default_json
        request.format = :json if params[:format].nil?
      end

      def auth_only!
        render :json: {}, status: 401 unless current_user
      end
    end
  end
 end

然后是Sessions:

module Api
  module V1
    class SessionsController < BaseController

      def create
        user = User.authenticate(params[:user_name], params[:password])
        if sign_in(user)
          set_up_cookie(user)
          render json: create_session_data, status: 201
        else
          invalid_user_crendentials
        end
      end
    end
  end
end

测试的设置方式相同,例如会话测试是:

require 'spec_helper'

describe Api::V1::SessionsController do
  before(:each) do
    @user = FactoryGirl.create(:user)
  end

  context "Create a session" do
    it "should NOT create a session" do
      post :create
      response.response_code.should == 401
    end
  end

end

错误:

'<module:V1>': uninitialized constant Api::V1::BaseController (NameError)

1 个答案:

答案 0 :(得分:0)

尝试稍微改变您的命名格式。

class Api::V1::BaseController < ApplicationController
  # code
end

class Api::V1::SessionsController < BaseController
  # might need to name this Api::V1::BaseController
end