简体   繁体   English

如何在Rails 5.2系统测试中填写或绕过HTTP Basic Auth?

[英]How do you fill in or bypass HTTP Basic Auth in Rails 5.2 System Tests?

I'm writing some tests for a site that is protected with http authentication on all pages. 我正在为所有页面上受http身份验证保护的网站编写一些测试。

I've managed to come across a way of bypassing it for controller tests by doing the following 通过执行以下操作,我设法找到了一种绕过控制器测试的方法

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

But how do I get past it for a system test? 但是如何进行系统测试呢? I've been searching around for hours to try and find a solution for this, but all of the suggestions I've found appear to be for older versions of Rails/Capybara and do not work. 我一直在搜索数小时以尝试找到解决方案,但是我发现的所有建议似乎都是针对较旧版本的Rails / Capybara的,因此不起作用。 There doesn't appear to be anything in the Rails testing documentation regarding this either. 在Rails测试文档中似乎也没有任何相关内容。

Okay, this seems to do the trick for me 好吧,这似乎对我有用

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

And then in my test methods I just do 然后在我的测试方法中

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

There's no need to mess with Capybara. 无需惹恼水豚。 Just add this method to ActiveSupport::TestCase in your test_helper.rb : 只需将此方法添加到test_helper.rb ActiveSupport::TestCase

def visit_authenticated(url)
  uri = URI.parse(url)
  uri.user = 'put_your_user_here'
  uri.password = 'put_your_password_here'
  visit uri
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Rails 5 控制器测试中测试或绕过 Basic Auth - How to test or bypass Basic Auth in Rails 5 testing of controllers 如何在Rails中使用http基本身份验证添加两个登录名? - How do you add two logins with http basic authentications in rails? 如何在Rails Metal中使用http基本身份验证? - How to use http basic auth in Rails Metal? Ruby on Rails:如何在多个控制器上进行HTTP身份验证? - Ruby on Rails: How do you do HTTP auth over multiple controllers? 如何使用Rails 5.2 wrap_parameters? - How do you use Rails 5.2 wrap_parameters? 在Rails 2.2+中测试HTTP Basic Auth - Testing HTTP Basic Auth in Rails 2.2+ Rails以编程方式设置基本的http Auth凭据 - Rails set basic http Auth Credentials programatically 在Rails 5.2中,如何配置系统测试以使用硒远程服务器? - In Rails 5.2 how can I configure my system tests to use a selenium remote server? 如果rails中未提供身份验证,请避免在http_basic_authenticate_with上使用HTTP 500 - Avoid HTTP 500 on http_basic_authenticate_with if no auth provided in rails 如何格式化POST以使用基本HTTP身份验证和设计Rails Gem创建用户 - How to format a POST to create User with Basic HTTP Auth and Devise Rails Gem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM