Skip to content

Instantly share code, notes, and snippets.

@ang3lkar
Last active November 15, 2020 05:41
Show Gist options
  • Save ang3lkar/bd1115c5e4b7a6fb5bbf to your computer and use it in GitHub Desktop.
Save ang3lkar/bd1115c5e4b7a6fb5bbf to your computer and use it in GitHub Desktop.
My notes on Rails integration testing

Due to a considerable lack of rails integration testing tutorials/guides, here are my notes.

Integration environment

Much better to have a separate environment for integration tests. Follow the Rails guide to create one. Be careful to edit the session domain in the integration.rb file if necessary:

config.session_store :cookie_store, key: '_workable_session', domain: 'test.host'

If the domain is different from what your app expects, you will be losing your session across your requests.

Create a separate helper file

In your integration tests, require a integration_helper.rb instead of a test_helper.rb file.

module ActionDispatch
  class IntegrationTest
    # Notice that I do NOT override the ActiveSupport::TestCase.fixture_path. Somewhere hidden in source code.
    ActionDispatch::IntegrationTest.fixture_path = "#{Rails.root}/test/integration/fixtures/"
    fixtures :all

    # Override host, by default it is example.com
    setup do
      host! 'test.host'
    end
  end
end

First test

require "test_helper"

class ExampleTest < ActionDispatch::IntegrationTest
  fixtures :people

  def test_login
    # get the login page
    get "/login"
    assert_equal 200, status

   # post the login and follow through to the home page
   post "/login", params: { username: people(:jamie).username,
      password: people(:jamie).password }
   follow_redirect!
   assert_equal 200, status
   assert_equal "/home", path
  end
end

The most thorough documentation can be found in the comments of the rails source code at https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/integration.rb

Understand that integration tests should not make assertions against the internal state of the web app. They should not make assertions on code variables, etc. They should only assert external output, like the response body and HTTP status codes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment