NameError:控制器中未初始化的常量,而rspec控制器测试

时间:2018-06-18 22:55:32

标签: ruby-on-rails ruby rspec rspec-rails rspec3

控制器代码

before_action :verify_request

def verify_request
  unless request.headers['Authorization'].present? && request.headers['Authorization'] == APIKEY["authorization_key"]
    render json: { message: "UnAuthorize Request" }, status: 401
  end
end

Rspec代码:

describe "GET #index" do
  it "returns 400 (empty query parameter)" do
    request.env["HTTP_AUTHORIZATION"] = "testing123"
    get :index
    expect(response).to have_http_status(400)
  end
end

我面临的问题是,在进行rspec测试时,控制器无法访问环境变量,测试失败。我该如何解决这个问题?

注意:我在config / authorization.yml中为所有环境定义了authorization_key,并且它在开发模式下工作,但没有在测试中工作。

我得到的错误是:

Failure/Error: unless request.headers['Authorization'].present? && request.headers['Authorization'] == APIKEY["authorization_key"]

 NameError:
   uninitialized constant V1::LocationController::APIKEY

1 个答案:

答案 0 :(得分:0)

您是否将require 'rails_helper'包含在CONTROLLER-NAME_controller_spec.rb