Back to Repositories

Testing Queue Message Cleanup Operations in Postal

This test suite evaluates the TidyQueuedMessagesTask functionality in the Postal server application, focusing on message queue cleanup operations. The tests verify the proper handling of stale locked messages and preservation of valid queue entries.

Test Coverage Overview

The test suite provides comprehensive coverage of queue message cleanup logic, specifically targeting message lock management. Key functionality tested includes:

  • Deletion of messages with stale locks
  • Preservation of unlocked messages
  • Handling of recently locked messages

The tests ensure the task correctly identifies and processes messages based on their lock status and age.

Implementation Analysis

The testing approach utilizes RSpec’s behavior-driven development patterns with factory-created test data. The implementation leverages let statements for dependency injection and subject blocks for clear test organization.

The tests employ factory_bot for test data generation and utilize RSpec’s expectation syntax for verifying both successful deletions and preserved records.

Technical Details

Testing tools and configuration include:

  • RSpec as the testing framework
  • Factory Bot for test data generation
  • TestLogger for logging verification
  • ActiveRecord for database interactions
  • Rails test helpers for database cleanup

Best Practices Demonstrated

The test suite exemplifies several testing best practices including isolated test cases, clear arrange-act-assert patterns, and comprehensive edge case coverage.

  • Proper test isolation and setup
  • Clear test case descriptions
  • Effective use of test doubles
  • Comprehensive error case handling

postalserver/postal

spec/scheduled_tasks/tidy_queued_messages_task_spec.rb

            
# frozen_string_literal: true

require "rails_helper"

RSpec.describe TidyQueuedMessagesTask do
  let(:logger) { TestLogger.new }

  subject(:task) { described_class.new(logger: logger) }

  describe "#call" do
    it "destroys queued messages with stale locks" do
      stale_message = create(:queued_message, locked_at: 2.days.ago, locked_by: "test")
      task.call
      expect { stale_message.reload }.to raise_error(ActiveRecord::RecordNotFound)
      expect(logger).to have_logged(/removing queued message \d+/)
    end

    it "does not destroy messages which are not locked" do
      message = create(:queued_message)
      task.call
      expect { message.reload }.not_to raise_error
    end

    it "does not destroy messages which where were locked less then the number of stale days" do
      message = create(:queued_message, locked_at: 10.minutes.ago, locked_by: "test")
      task.call
      expect { message.reload }.not_to raise_error
    end
  end
end