When you’re interested in testing the actual SQL queries generated by ActiveRecord, rather than just what’s returned from the database, you can capture them using ActiveSupport::Notifications.

module QueryCapturing
  IGNORED_QUERIES = ["SCHEMA", "TRANSACTION"]

  def capture_queries
    captured_queries = []
    subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |event|
      captured_queries << event.payload[:sql] unless IGNORED_QUERIES.include?(event.name)
    end
    yield captured_queries
  ensure ActiveSupport::Notifications.unsubscribe(subscriber)
  end
end
class ServiceMetadata::QueryCommentsTest < Minitest::Test
  include QueryCapturing

  def test_annotates_queries_with_metadata_comments
    capture_queries do |queries|
      ServiceMetadata::QueryComments.comment { Comment.all.load }

      assert queries.all? { |q| q.match?(/\/\*.*?origin_service: my_service.*?\*\//m) }
    end
  end
end