【问题标题】:Change request environment variables in Rails integration testing在 Rails 集成测试中更改请求环境变量
【发布时间】:2011-03-05 02:23:27
【问题描述】:

我已经编写了一个功能测试,它改变了请求对象的一些环境变量来模拟用户已经登录。

require 'test_helper'
class BeesControllerTest < ActionController::TestCase

  # See that the index page gets called correctly.
  def test_get_index

    @request.env['HTTPS'] = "on"
    @request.env['SERVER_NAME'] = "sandbox.example.com"
    @request.env['REMOTE_USER'] = "joeuser" # Authn/Authz done via REMOTE_USER

    get :index
    assert_response :success
    assert_not_nil(assigns(:bees))
    assert_select "title", "Bees and Honey"
  end
end

功能测试工作正常。

现在我想做一些类似的事情作为集成测试的一部分。这是我尝试过的:

require 'test_helper'
class CreateBeeTest < ActionController::IntegrationTest
  fixtures :bees

  def test_create
    @request.env['HTTPS'] = "on"
    @request.env['SERVER_NAME'] = "sandbox.example.com"
    @request.env['REMOTE_USER'] = "joeuser" # Authn/Authz done via REMOTE_USER

    https?

    get "/"
    assert_response :success
    [... more ...]
  end
end

我收到一条错误消息,抱怨 @request 为零。我怀疑这与会话对象有关,但我不确定如何让它工作。

【问题讨论】:

  • @request.env['HTTPS'] = "on" 行抱怨您不能将 env 方法应用于 nil 值。
  • 这是一个三年前提交给 Rails 的补丁,解决了这个问题:dev.rubyonrails.org/ticket/8209

标签: ruby-on-rails environment-variables integration-testing


【解决方案1】:

您可以在集成测试中设置 HTTPS

https!

并设置主机名:

host! "sandbox.example.com"

这可能相当于你想做的事?

这在 Rails 指南Rails guides中有描述

【讨论】:

  • 但是如何设置例如request.remote_ipActionDispatch::Integration::Session中没有类似的特殊方法
  • 我也来到这里寻找设置request.remote_ip 的方法,它使用这样的环境参数对我有用:get "/", params: params, env: { 'REMOTE_ADDR' =&gt; '1.2.3.4' }
【解决方案2】:

您可以通过参数将请求变量更改为post方法。

对于您的情况,方法 test_create 将是:

def test_create
  https!

  get "/", nil, { 'SERVER_NAME'] => "sandbox.example.com", 'REMOTE_USER'] => "joeuser" }

  assert_response :success
  [... more ...]
end

将发布请求设置为原始数据也是如此:

post root_path, nil, { 'RAW_POST_DATA' => 'some string' }

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2021-06-01
    • 2022-11-20
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多