2015-11-05 48 views
0

嘿傢伙任何人都可以找到我哪裏出錯了?我創建了一個API端點,預計將從另一個網站使用參數調用。從這些參數我打算在我的應用程序中找到用戶並更新該用戶的屬性。這是我的控制器的樣子:Rspec得到請求沒有擊中控制器(401未經授權的錯誤)

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應該找到與用戶相應的手機號碼並將他們的「監護人驗證」屬性更改爲「false」。但是,當我運行規格時,它會在測試日誌中引發此錯誤:

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) 

但是,該功能本身能正常工作,但該規範不適用。任何人都知道爲什麼?

回答

0

在您發送請求之前,您必須將授權標頭添加到請求中。

實施例:

request.headers["Authorization"] = "..." 
request.headers["X-Api-Key"] = "..." 
request.headers["Content-Type"] = "..." 
相關問題