7.4. Integration Tests

Integration tests are tests that work like functional tests but can go over several controllers and additionally analyze the content of a generated view. So you can use them to recreate complex workflows within the Rails application. As an example, we will write an integration test that tries to create a new user via the Web GUI, but omits the login_name and consequently gets corresponding flash error messages.
A rake generate scaffold generates unit and functional tests, but not integration tests. You can either do this manually in the directory test/integration/ or more comfortably with rails generate integration_test. So let's create an integration test:
$ rails generate integration_test invalid_new_user_workflow
      invoke  test_unit
      create    test/integration/invalid_new_user_workflow_test.rb
We now populate this file test/integration/invalid_new_user_workflow_test.rb with the following test:
require 'test_helper'

class InvalidNewUserWorkflowTest < ActionDispatch::IntegrationTest
  fixtures :all

  test 'try to create a new empty user and check for flash error messages' do
    get '/users/new'
    assert_response :success

    post_via_redirect "/users", user: {:last_name => users(:one).last_name} 
    assert_equal '/users', path
    assert_select 'li', "Login name can&#39;t be blank"
    assert_select 'li', "Login name is too short (minimum is 10 characters)"
The magic of the integration test lies amongst others in the method post_via_redirect, with which you can carry on after a post in the test. This method is only available within an integration test.
All integration tests can be executed with rake test:integration. Let's have a go:
$ rake test:integration
Run options: --seed 61457

# Running tests:


Finished tests in 0.146213s, 6.8393 tests/s, 27.3573 assertions/s.

1 tests, 4 assertions, 0 failures, 0 errors, 0 skips
The example clearly shows that you can program much without manually using a web browser to try it out. Once you have written a test for the corresponding workflow, you can rely in future on the fact that it will run through and you don't have to try it out manually in the browser as well.

Thank you for your support and the visibility by linking to this website on Twitter and Facebook. That helps a lot!