Ruby-on-rails Rails/Rspec 使用 http 基本身份验证通过测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3768718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:15:06  来源:igfitidea点击:

Rails/Rspec Make tests pass with http basic authentication

ruby-on-railsrspechttp-authentication

提问by benoitr

Here my http basic authentication in the application controller file (application_controller.rb)

这是我在应用程序控制器文件 (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

and the default test for the index action of my home controller (spec/controllers/home_controller_spec.rb)

以及我的家庭控制器的索引操作的默认测试(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

Test doesn't run because of the authentication method. I could comment "before_filter :authenticate" to run them but I would like to know if there is way to make them worked with the method.

由于身份验证方法,测试未运行。我可以评论“before_filter :authenticate”来运行它们,但我想知道是否有办法让它们使用该方法。

Thank you!

谢谢!

回答by iwasrobbed

Update(2013): Matt Connolly has provided a GIST which also works for request and controller specs: http://gist.github.com/4158961

更新(2013 年):Matt Connolly 提供了一个 GIST,它也适用于请求和控制器规范:http: //gist.github.com/4158961



Another way of doing this if you have many tests to run and don't want to include it everytime (DRYer code):

如果您有许多测试要运行并且不想每次都包含它(DRYer 代码),另一种方法是:

Create a /spec/support/auth_helper.rb file:

创建一个 /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

In your test spec file:

在您的测试规范文件中:

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

Credit here

信用在这里

回答by benoitr

Sorry I didn't seek enough, the solution seems to be the following:

对不起,我没有寻求足够的,解决方案似乎如下:

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

回答by Daniel Garmoshka

Some answers suggest to set request.envwhich is unsafe, because request can be niland you will end up with private method env' called for nil:NilClass, especially when run single tests with rspec -e

一些答案建议设置request.env哪个是不安全的,因为 request 可以是nil,你最终会得到private method env' called for nil:NilClass,尤其是在运行单个测试时rspec -e

Correct approach will be:

正确的做法是:

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

回答by deepwinter

When using Rspec to test Grape APIs, the following syntax works

使用 Rspec 测试 Grape API 时,以下语法有效

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

where valid_session is

valid_session 在哪里

{'HTTP_AUTHORIZATION' => credentials}

and

credentials = ActionController::HttpAuthentication::Token.encode_credentials("test_access1")

回答by madcow

These are great solutions for controller and request specs.

这些是控制器和请求规范的绝佳解决方案。

For feature tests using Capybara, here is a solution to make HTTP Basic authentication work:

对于使用 Capybara 的功能测试,以下是使 HTTP 基本身份验证工作的解决方案:

spec/support/when_authenticated.rb

规范/支持/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

Then, in your spec:

然后,在您的规范中:

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

  # test examples
end