Back to Repositories

Testing I18n Message Inheritance in Devise Controllers

This test suite validates the internationalization (i18n) message handling in inherited Devise controllers. It specifically tests how translation scopes are inherited and overridden when extending the Devise::SessionsController.

Test Coverage Overview

The test suite covers two main scenarios for i18n message handling in Devise controllers:
  • Inheritance of default i18n scope from Devise::SessionsController
  • Custom override of translation scope in inherited controllers
  • Flash message handling with proper i18n scoping

Implementation Analysis

The testing approach uses inheritance patterns to verify i18n behavior across controller hierarchies. It implements mock Warden authentication and Devise mapping setup for controller testing.
  • Controller inheritance verification
  • Translation scope customization
  • Flash message integration testing

Technical Details

Testing infrastructure includes:
  • Devise::ControllerTestCase as base test class
  • OpenStruct for Warden authentication mocking
  • I18n expectation testing with message and scope verification
  • Custom controller implementations for inheritance testing

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Proper test isolation through setup methods
  • Clear test case organization for different scenarios
  • Explicit verification of i18n message parameters
  • Effective use of inheritance for testing controller hierarchies

heartcombo/devise

test/controllers/inherited_controller_i18n_messages_test.rb

            
# frozen_string_literal: true

require 'test_helper'

class SessionsInheritedController < Devise::SessionsController
  def test_i18n_scope
    set_flash_message(:notice, :signed_in)
  end
end

class AnotherInheritedController < SessionsInheritedController
  protected

  def translation_scope
    'another'
  end
end

class InheritedControllerTest < Devise::ControllerTestCase
  tests SessionsInheritedController

  def setup
    @mock_warden = OpenStruct.new
    @controller.request.env['warden'] = @mock_warden
    @controller.request.env['devise.mapping'] = Devise.mappings[:user]
  end

  test 'I18n scope is inherited from Devise::Sessions' do
    I18n.expects(:t).with do |message, options|
      message == 'user.signed_in' &&
        options[:scope] == 'devise.sessions'
    end
    @controller.test_i18n_scope
  end
end

class AnotherInheritedControllerTest < Devise::ControllerTestCase
  tests AnotherInheritedController

  def setup
    @mock_warden = OpenStruct.new
    @controller.request.env['warden'] = @mock_warden
    @controller.request.env['devise.mapping'] = Devise.mappings[:user]
  end

  test 'I18n scope is overridden' do
    I18n.expects(:t).with do |message, options|
      message == 'user.signed_in' &&
        options[:scope] == 'another'
    end
    @controller.test_i18n_scope
  end
end