簡體   English   中英

RSpec POST請求的Devise和Factorybot身份驗證

[英]Devise & Factorybot authentication for RSpec POST request

使用devise_token_auth,Factorygirl和RSpec進行設置。

嘗試登錄用戶並發出發布請求,但我收到401未經授權的回復。

/spec/controllers/scripts_controller_spec.rb

module Api::V1
RSpec.describe ScriptsController, type: :controller do

  let(:user) { FactoryBot.create(:user)}

  let(:valid_attributes) {
    {name: 'YWoodcutter', skill: 'Woodcutting', bot_for: 'TRiBot', game_for: "Oldschool Runescape 07", user_id: user.id}
  }
...
describe "POST #create" do
    context "with valid params" do
      it "creates a new Script" do
        sign_in user
        expect {
          post :create, params: {script: valid_attributes}
        }.to change(Script, :count).by(1)
      end

      it "renders a JSON response with the new script" do
        sign_in user
        post :create, params: {script: valid_attributes}
        expect(response).to have_http_status(:created)
        expect(response.content_type).to eq('application/json')
        expect(response.location).to eq(script_url(Script.last))
      end
    end

RSpec測試結果:失敗:

1)使用有效參數的Api :: V1 :: ScriptsController POST #create創建新的腳本失敗/錯誤:期望{post:create,params:{script:valid_attributes}} .to((Script,:count).by(1 )

  expected #count to have changed by 1, but was changed by 0 # ./spec/controllers/scripts_controller_spec.rb:72:in `block (4 levels) in <module:V1>' 

2)具有有效參數的Api :: V1 :: ScriptsController POST #create使用新腳本呈現JSON響應失敗/錯誤:Expect(response).to have_http_status(:created)期望響應具有狀態代碼:created(201)但這是:未經授權的(401)#./spec/controllers/scripts_controller_spec.rb:80:在'

好奇為什么POST #create沒有觸發。 實際上,我從種子數據中使用了相同的值,效果很好。

還想知道為什么即使在調用Devise的signn_in用戶之后,請求仍未被授權的原因。

謝謝。

編輯:Devise Wiki提及映射 ,我應該在某處稱這行嗎?

@request.env["devise.mapping"] = Devise.mappings[:user]

devise_token_auth要求您在標頭中包含令牌,我在help文件夾中放置了一個幫助器:

def auth_request(user)
  sign_in user
  request.headers.merge!(user.create_new_auth_token)
end

然后在您的規格中調用auth_request user而不是sign_in user

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM