我想在rails 5中测试控制器,它的基本身份验证被激活。
current official instruction中解释的方式(截至2018-10-14)由于某种原因不起作用。
问答“Testing HTTP Basic Auth in Rails 2.2+”对于rails 5来说似乎太旧了(至少对于默认值来说是这样)。
下面是一个简单的例子来重现这个案例。
我用scaffold从新安装的rails(最新稳定版本5.2.1)制作了一个文章模型和相关资源:

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

并在控制器中添加了基本的auth函数,遵循official guide;那么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

official instruction解释了测试基本身份验证的方法;您可以添加
request.headers['Authorization']在控制器测试文件中的setup块中,我做到了:
# /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 <class:ArticlesControllerTest>'

bin/rails test test/controllers/articles_controller_test.rb:10

显然,request方法返回nil,因此request.headers['Authorization']失败。如果将语句放在“testing index”块的顶部,则相同。
我发现request在运行get articles_url之后返回了一个正确的值,但是到那个时候已经太晚了;我的意思是,身份验证到那个时候已经失败了(很明显)。通过一些google,似乎有些人使用了@request@response来代替,但我也发现他们的情况与request完全相同(期望如此?),也就是说,它们在get之前为零。
在Rails5中,如何绕过或测试控制器测试或集成测试中的基本身份验证?
编辑:
current official instruction(截至2018-10-14)”显然是错误的。参阅the answer

最佳答案

测试文档were incorrecthave been updated尚未发布。updated docs显示:
注意:如果遵循基本身份验证部分中的步骤,则需要向每个请求头添加授权,以使所有测试通过:
post articles_url, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }

关于ruby-on-rails - 如何在Rails 5 Controller 测试中测试或绕过Basic Auth,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52803228/

10-11 03:01
查看更多