Back to Repositories

Testing Session Authentication and Access Control in Maybe Finance

This test suite validates session management functionality in a Ruby on Rails application, covering user authentication flows, access control, and admin privileges. The tests ensure proper login/logout behavior and authorization checks for different user roles.

Test Coverage Overview

The test suite provides comprehensive coverage of session-related functionality including:
  • User authentication with valid and invalid credentials
  • Session creation and destruction
  • Access control for admin-specific routes
  • Flash message verification
  • Redirect behavior after authentication actions

Implementation Analysis

The testing approach utilizes ActionDispatch::IntegrationTest for end-to-end session verification. It employs fixtures for user data and implements custom sign_in helper methods. The tests validate both successful paths and error scenarios, ensuring robust session handling.

Key patterns include response status assertion, flash message verification, and redirect chain validation.

Technical Details

Testing Tools & Configuration:
  • Minitest framework with Rails integration testing
  • ActionDispatch for HTTP request simulation
  • Fixture-based test data management
  • Custom authentication helpers
  • Flash message assertion utilities

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Isolated test setup using fixtures
  • Comprehensive error case coverage
  • Clear test naming conventions
  • Proper separation of authentication scenarios
  • Validation of both positive and negative paths
  • Explicit status code checking

maybe-finance/maybe

test/controllers/sessions_controller_test.rb

            
require "test_helper"

class SessionsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @user = users(:family_admin)
  end

  test "login page" do
    get new_session_url
    assert_response :success
  end

  test "can sign in" do
    sign_in @user
    assert_redirected_to root_url

    get root_url
    assert_response :success
  end

  test "fails to sign in with bad password" do
    post sessions_url, params: { email: @user.email, password: "bad" }
    assert_response :unprocessable_entity
    assert_equal "Invalid email or password.", flash[:alert]
  end

  test "can sign out" do
    sign_in @user

    delete session_url(@user.sessions.order(:created_at).last)
    assert_redirected_to new_session_path
    assert_equal "You have signed out successfully.", flash[:notice]
  end

  test "super admins can access the jobs page" do
    sign_in users(:maybe_support_staff)
    get good_job_url
    assert_redirected_to "http://www.example.com/good_job/jobs?locale=en"
  end

  test "non-super admins cannot access the jobs page" do
    get good_job_url
    assert_response :not_found
  end
end