[英]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.