Rspec获取请求未命中控制器(401未经授权的错误)

时间:2015-11-05 08:47:22

标签: ruby-on-rails api rspec get endpoint

嘿伙计们谁能找到我错的地方?我已经创建了一个API端点,期望从另一个带参数的网站调用。根据这些参数,我意味着在我的应用中找到用户并更新该用户的属性。这就是我的控制器的外观:

class Vodacom::Api::V1::SmsReceiverController < ApplicationController
  protect_from_forgery :except => [:suspend_account]

  def suspend_account
   logger.info "PARAMS: #{params.inspect}"
   @user = User.find_by(guardian_number: localize_number(vodacom_params[:num]), cell_number: vodacom_params[:mesg])
   begin
    @user.update(guardian_verified: false) if @user.older_than_18? == false
    render status: :ok, json: { message: "Account Deactivated" }
   rescue
     render status: :ok, json: { message: "Couldn't find user" }
    end
  end

 def localize_number(num)
  num = num.sub(/^../, '0')
 end

 private

 def vodacom_params
  params.permit(:num, :mesg, :prem, :tonum, :id)
 end
end

我的路线如下:

 namespace :vodacom do
    namespace :api do
      namespace :v1 do
        get "/suspend_account", to: "sms_receiver#suspend_account"
      end
    end
  end

我对此功能的规范如下所示:

require 'rails_helper'

RSpec.describe Vodacom::Api::V1::SmsReceiverController, :type => :controller do

  describe "When the correct parameters are sent to the SMS receiver controller" do
    let(:user){ create(:user, guardian_number: "0798900606", cell_number: "0798900606")}
    let(:params){ {prem: "30911", mesg: "0798900606", num: "27798900606", tonum: "082007005922721", id: "1122365"} }

    it "should receive a query string with attributes" do
      expect(suspend_user_account.request.env['QUERY_STRING']).to eq("id=1122365&mesg=0798900606&num=27798900606&prem=30911&tonum=082007005922721")
    end

    it "should find and disable the user's account " do
      get :suspend_account, params
      user.reload
      expect(user.guardian_verified).to eq(false)
    end

  end
end

Api应该找到具有相应手机号码的用户并更改他们的&#34;监护人已验证&#34;属性为&#34; false&#34;。但是,当我运行规范时,它会在测试日志中抛出此错误:

Processing by Vodacom::Api::V1::SmsReceiverController#suspend_account as HTML
  Parameters: {"prem"=>"30911", "mesg"=>"0798900606", "num"=>"27798900606", "tonum"=>"082007005922721", "id"=>"1122365"}
Completed 401 Unauthorized in 6ms (ActiveRecord: 0.0ms)
  Rendered text template (0.0ms)

但是,功能本身有效,但规格并不适用。有谁知道为什么?

1 个答案:

答案 0 :(得分:0)

在发送请求之前,您必须在请求中添加授权标头。

示例:

 request.headers["Authorization"] = "..."
 request.headers["X-Api-Key"] = "..."
 request.headers["Content-Type"] = "..."