如何在Rails 5测试控制器中测试或绕过Basic Auth

我想在Rails 5中测试激活基本身份validation的控制器。 当前官方指令 (截至2018-10-14)中解释的方式由于某种原因不起作用。 问题与解答 “ 在Rails 2.2+中测试HTTP基本身份validation ”对于Rails 5来说似乎太旧了(至少对于默认值而言)。

这是重现案例的简化示例。
我通过全新安装的Rails(最新的稳定版本5.2.1)通过脚手架制作了一个文章模型和相关资源:

bin/rails g scaffold Article title:string content:text 

并根据官方指南将基本的authfunction添加到控制器; 那么ArticlesController是这样的,当然有效:

 # /app/controllers/articles_controller.rb class ArticlesController < ApplicationController http_basic_authenticate_with name: "user1", password: "pass" before_action :set_article, only: [:show, :edit, :update, :destroy] def index @articles = Article.all end end 

官方说明解释了测试基本认证的方法; 你在控制器的测试文件中的setup块中添加了request.headers['Authorization'] ,我做了:

 # /test/controllers/articles_controller_test.rb require 'test_helper' class ArticlesControllerTest < ActionDispatch::IntegrationTest setup do request.headers['Authorization'] = ActionController::HttpAuthentication::Basic.encode_credentials("user1", "pass") @article = articles(:one) end test "should get index" do get articles_url assert_response :success end end 

但是, bin/rails test失败如下:

 # Running: E Error: ArticlesControllerTest#test_should_get_index: NoMethodError: undefined method `headers' for nil:NilClass test/controllers/articles_controller_test.rb:5:in `block in ' bin/rails test test/controllers/articles_controller_test.rb:10 

显然, request方法返回nil,因此request.headers['Authorization']失败。 如果语句放在’testing-index’块的顶部,则相同。

我发现运行get articles_url 之后 request返回了一个正确的值,但到那时已经太晚了; 我的意思是,到那时候身份validation已经失败了(显然)。 通过一些谷歌搜索,似乎有些人使用@request@response代替,但我也发现它们与request完全处于相同的情况(预期?),也就是说,它们在get之前是零。

在Rails 5中测试控制器或集成测试时绕过或测试Basic Auth的方法是什么?

编辑:
目前的官方指令 (截至2018-10-14)”显然是错误的。 看到答案 。

测试文档不正确 , 已更新但尚未发布。 更新的文档为:

注意:如果您按照“基本身份validation”部分中的步骤操作,则需要向每个请求标头添加授权以获取所有传递的测试:

post articles_url, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }