rlandster
rlandster

Reputation: 7835

Change request environment variables in Rails integration testing

I have written a functional test that changes some of the request object's environment variables to simulate a user has logged in.

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

The functional test works fine.

Now I want to do something similar as part of integration testing. Here is what I tried:

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

I get an error complaining that @request is nil. I suspect this has something to do with the session object, but I am not sure how to get it to work.

Upvotes: 8

Views: 3436

Answers (2)

Alexey Chernikov
Alexey Chernikov

Reputation: 1885

You can change request variables via parameters to post method.

For your case, method test_create will be:

def test_create
  https!

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

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

Same works for setting post request to raw data:

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

Upvotes: 1

Roger Ertesvag
Roger Ertesvag

Reputation: 1794

You can set HTTPS in integration tests with

https!

And set the host name with:

host! "sandbox.example.com"

Which may be equivalent to what you want to do?

This is described in the Rails guides Rails guides

Upvotes: 3

Related Questions