我想在激活基本身份验证的 Rails 5 中测试 Controller 。 current official instruction中解释的方式(截至 2018-10-14)由于某种原因不起作用。 问答“Testing HTTP Basic Auth in Rails 2.2+”对于 Rails 5 来说似乎太旧了(至少对于默认值而言)。
这里是重现案例的简化示例。
我通过全新安装的 Rails(最新稳定版本 5.2.1)通过脚手架制作了一个文章模型和相关资源:
bin/rails g scaffold Article title:string content:text
并在 official guide 之后向 Controller 添加了基本的身份验证功能。 ;然后 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']
在 Controller 测试文件的 setup
block 中,我这样做了:
# /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' block 的顶部,则相同。
我发现 request
在 get articles_url
运行后返回了一个正确的值,但那时已经太晚了;我的意思是,到那时身份验证已经失败(很明显)。通过一些谷歌搜索,似乎有些人使用 @request
和 @response
来代替,但我也发现它们与 完全相同request
(预期?),即在 get
之前它们为 nil。
在 Rails 5 的 Controller 测试或集成测试中绕过或测试 Basic Auth 的方法是什么?
编辑:
“current official instruction(截至 2018 年 10 月 14 日)”显然是错误的。参见 the answer .
最佳答案
测试文档were incorrect和 have been updated但尚未发布。 updated docs阅读:
NOTE: If you followed the steps in the Basic Authentication section, you'll need to add authorization to every request header to get all the tests passing:
post articles_url, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
关于ruby-on-rails - 如何在 Controller 的 Rails 5 测试中测试或绕过 Basic Auth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803228/