[英]Skip Rails http_basic_authenticate_with in RSpec test
我正在研究MVP(最低可行產品)。 為了提供一種更簡單的方法來保護管理頁面,我只是將http_basic_authenticate_with添加到我的AdminController中。
問題是當我想測試我的AdminController時,我得到“未授權”(401)因為沒有登錄。
在這種情況下,測試身份驗證無關緊要 - 它只是暫時的,一旦我進入下一個sprint,它就會被刪除 - 所以我試圖在RSpec中跳過它。
問題是我嘗試了很多方法,但似乎都沒有。
例如,我嘗試修改http_basic_authenticate_with以避免身份驗證。 像這樣:
require 'spec_helper'
module ActionController
module HttpAuthentication
module Basic
def http_basic_authenticate_with(*args)
end
end
end
end
describe Admin::SubscribersController do
describe "GET 'index'" do
it "should be OK" do
get 'index'
response.should be_successful
end
end
end
但是當我運行它時,對於那個簡單的測試,它仍然會返回“false”。
順便說一句,為了簡化這個測試,我只在我的AdminController上有一個空的索引操作和一個空視圖(index.html.erb)。
最后,我得到了它的工作。
文檔中陳述的內容對我不起作用:
get 'index', nil, 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials("admin", "password")
所以我嘗試了一種“舊的”方法,即設置request.env ['HTTP_AUTHORIZATION'] :
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials("admin","password")
沒有其他解決方案有效,所以我將與此保持同步。
謝謝。
如果可以跳過對控制器的所有測試的身份驗證,這是我在當前項目中使用的技術。
unless Rails.env.test?
http_basic_authenticate_with name: "slothbear", password: "kuniklo"
end
在Rails 5.x中,這有效:
allow(subject).to receive(:authenticate_or_request_with_http_basic)
.with(anything).and_return true
在Rails 6.x中,這有效:
allow(subject).to receive(:http_basic_authenticate_or_request_with)
.with(anything).and_return true
這是因為http_basic_authenticate_with
是一個類級方法,它添加了一個實際調用這兩種方法之一的before_action
。
您可以通過在這里查看Rails 6的 http_authentication.rb
或Rails 5來查看使用哪一個
您甚至可以測試身份驗證。 編寫未經身份驗證(現在是)並經過身份驗證的測試。 請參閱在Rails 2.2+中測試HTTP Basic Auth,它應該有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.