首页 > 解决方案 > 在 Rails 5.2 系统测试中如何填写或绕过 HTTP Basic Auth?

问题描述

我正在为一个在所有页面上都受 http 身份验证保护的站点编写一些测试。

通过执行以下操作,我设法找到了一种绕过它进行控制器测试的方法

get exams_url, headers: {'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials('admin','admin') }

但是我如何通过它进行系统测试呢?我一直在寻找几个小时来尝试找到解决方案,但我发现的所有建议似乎都是针对旧版本的 Rails/Capybara 并且不起作用。Rails 测试文档中似乎也没有关于此的任何内容。

标签: ruby-on-railsautomated-testscapybara

解决方案


好的,这似乎对我有用

def visit_with_http_auth(path)
  username = 'admin'
  password = 'admin'
  visit "http://#{username}:#{password}@#{Capybara.current_session.server.host}:# 
  {Capybara.current_session.server.port}#{path}"
end

然后在我的测试方法中我只是做

test "visiting the index" do
  visit_with_http_auth questions_path
  assert_selector "h1", text: "Questions"
end

推荐阅读