【问题标题】:How do you fill in or bypass HTTP Basic Auth in Rails 5.2 System Tests?在 Rails 5.2 系统测试中如何填写或绕过 HTTP Basic Auth?
【发布时间】:2019-04-04 13:52:44
【问题描述】:

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

通过执行以下操作,我设法绕过它进行控制器测试

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

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

【问题讨论】:

    标签: ruby-on-rails automated-tests capybara


    【解决方案1】:

    好吧,这似乎对我有用

    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
    

    【讨论】:

    • 我编辑将Capybara.current_session替换为page
    【解决方案2】:

    没必要惹水豚。只需将此方法添加到您的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2020-04-09
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多