74

ここでは、アプリケーション コントローラー ファイル (application_controller.rb) での http 基本認証を示します。

before_filter :authenticate

protected

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == "username" && password == "password"  
  end
end

私のホームコントローラーのインデックスアクションのデフォルトテスト(spec/controllers/home_controller_spec.rb)

require 'spec_helper'

describe HomeController do

describe "GET 'index'" do
  it "should be successful" do
    get 'index'
    response.should be_success
  end
end

認証方法が原因で、テストが実行されません。「before_filter :authenticate」とコメントして実行することもできますが、メソッドでそれらを機能させる方法があるかどうか知りたいです。

ありがとうございました!

4

7 に答える 7

141

更新(2013): Matt Connolly は、リクエストとコントローラーの仕様にも機能する GIST を提供しました: http://gist.github.com/4158961


実行するテストが多く、毎回含めたくない場合の別の方法 (DRYer コード):

/spec/support/auth_helper.rb ファイルを作成します。

module AuthHelper
  def http_login
    user = 'username'
    pw = 'password'
    request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user,pw)
  end  
end

テスト仕様ファイルで:

describe HomeController do
  render_views

  # login to http basic auth
  include AuthHelper
  before(:each) do
    http_login
  end

  describe "GET 'index'" do
    it "should be successful" do
      get 'index'
      response.should be_success
    end
  end

end

クレジットはこちら

于 2011-03-08T22:21:35.803 に答える
20

申し訳ありませんが、十分に求めていませんでした。解決策は次のようです。

describe "GET 'index'" do
  it "should be successful" do
    @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
    get 'index'
    response.should be_success
  end
end
于 2010-09-22T11:36:15.370 に答える
8

特に単一のテストrequest.envnilprivate method env' called for nil:NilClassrspec -e

正しいアプローチは次のとおりです。

def http_login
  user = 'user'
  password = 'passw'
  {
    HTTP_AUTHORIZATION: ActionController::HttpAuthentication::Basic.encode_credentials(user,password)
  }
end

get 'index', nil, http_login

post 'index', {data: 'post-data'}, http_login
于 2016-12-22T19:56:23.920 に答える
4

Rspec を使用して Grape API をテストする場合、次の構文が機能します。

        post :create, {:entry => valid_attributes}, valid_session

ここで、valid_session は

{'HTTP_AUTHORIZATION' => credentials}

credentials = ActionController::HttpAuthentication::Token.encode_credentials("test_access1")
于 2014-06-19T06:14:04.287 に答える
4

私の場合、Rails 6 では、..のような rspec get メソッドにキーワード引数が必要です。get route, params: params, headers: headers

認証ヘルパー メソッド

module AuthHelper
  def headers(options = {})
    user = ENV['BASIC_AUTH_USER']
    pw = ENV['BASIC_AUTH_PASSWORD']

    { HTTP_AUTHORIZATION: ActionController::HttpAuthentication::Basic.encode_credentials(user,pw) }
  end
  def auth_get(route, params = {})
    get route, params: params, headers: headers
  end
end

そしてrspecリクエストテスト。

describe HomeController, type: :request do    
  include AuthHelper

  describe "GET 'index'" do
    it "should be successful" do
      auth_get 'index'
      expect(response).to be_successful
    end
  end

end
于 2021-08-05T15:51:57.290 に答える
3

これらは、コントローラーとリクエスト仕様の優れたソリューションです。

Capybara を使用した機能テストでは、HTTP 基本認証を機能させるためのソリューションを次に示します。

仕様/サポート/when_authenticated.rb

RSpec.shared_context 'When authenticated' do
  background do
    authenticate
  end

  def authenticate
    if page.driver.browser.respond_to?(:authorize)
      # When headless
      page.driver.browser.authorize(username, password)
    else
      # When javascript test
      visit "http://#{username}:#{password}@#{host}:#{port}/"     
     end
  end

  def username
    # Your value here. Replace with string or config location
    Rails.application.secrets.http_auth_username
  end

  def password
    # Your value here. Replace with string or config location
    Rails.application.secrets.http_auth_password
  end

  def host
    Capybara.current_session.server.host
  end

  def port
    Capybara.current_session.server.port
  end
end

次に、仕様で:

feature 'User does something' do
  include_context 'When authenticated'

  # test examples
end
于 2015-09-09T17:02:41.263 に答える
0

私の解決策:

stub_request(method, url).with(
  headers: { 'Authorization' => /Basic */ }
).to_return(
  status: status, body: 'stubbed response', headers: {}
)

gem webmockを使う

変更することで検証を強化できます:

/Basic */ -> "Basic #{Base64.strict_encode64([user,pass].join(':')).chomp}"

URL - 正規表現にすることができます

于 2020-07-21T08:58:47.543 に答える