0
0
Ruby on Railsframework~5 mins

Integration tests in Ruby on Rails

Choose your learning style9 modes available
Introduction

Integration tests check if different parts of your Rails app work well together. They help find problems that unit tests might miss.

When you want to test how a user logs in and sees their dashboard.
When you need to check if submitting a form saves data correctly and shows a confirmation.
When you want to verify that clicking links moves between pages as expected.
When you want to test how multiple models and controllers interact in a real scenario.
Syntax
Ruby on Rails
require 'test_helper'

class UserFlowsTest < ActionDispatch::IntegrationTest
  test "user can log in and see dashboard" do
    get login_path
    assert_response :success
    post login_path, params: { session: { email: 'user@example.com', password: 'password' } }
    follow_redirect!
    assert_select 'h1', 'Dashboard'
  end
end

Integration tests use ActionDispatch::IntegrationTest in Rails.

You simulate user actions like visiting pages, submitting forms, and following redirects.

Examples
Visit the home page and check if it loads successfully.
Ruby on Rails
get root_path
assert_response :success
Submit a form to create a user and check if it redirects to the new user's page.
Ruby on Rails
post users_path, params: { user: { name: 'Alice', email: 'alice@example.com' } }
assert_redirected_to user_path(User.last)
After a redirect, check if the page shows a welcome message inside a paragraph with class 'notice'.
Ruby on Rails
follow_redirect!
assert_select 'p.notice', 'Welcome!'
Sample Program

This test simulates a user visiting the login page, submitting their email and password, and then seeing a welcome message on the redirected page.

Ruby on Rails
require 'test_helper'

class LoginFlowTest < ActionDispatch::IntegrationTest
  test "user logs in and sees welcome message" do
    get login_path
    assert_response :success

    post login_path, params: { session: { email: 'user@example.com', password: 'password' } }
    assert_response :redirect

    follow_redirect!
    assert_response :success
    assert_select 'h1', 'Welcome, user@example.com!'
  end
end
OutputSuccess
Important Notes

Integration tests are slower than unit tests because they simulate real user actions.

Use fixtures or factories to set up test data before running integration tests.

Check HTML elements with assert_select to verify page content.

Summary

Integration tests check how parts of your app work together from a user's view.

They simulate visiting pages, submitting forms, and following redirects.

Use ActionDispatch::IntegrationTest and helper methods like get, post, and assert_select.