在Rails集成测试中更改请求环境变量

rla*_*ter 7 integration-testing ruby-on-rails environment-variables

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

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
Run Code Online (Sandbox Code Playgroud)

功能测试工作正常.

现在我想做一些与集成测试相似的事情.这是我尝试过的:

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
Run Code Online (Sandbox Code Playgroud)

我得到一个错误抱怨@request是零.我怀疑这与session对象有关,但我不知道如何让它工作.

Rog*_*vag 3

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

https!
Run Code Online (Sandbox Code Playgroud)

并设置主机名:

host! "sandbox.example.com"
Run Code Online (Sandbox Code Playgroud)

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

Rails指南中对此进行了描述

  • 但是如何设置例如“request.remote_ip”?`ActionDispatch::Integration::Session` 中没有类似的特殊方法 (4认同)