Module: RailsMemoryProfiler::TestHelper

Extended by:
TestHelper
Included in:
TestHelper
Defined in:
lib/rails_memory_profiler/test_helper.rb

Overview

Utility methods for asserting allocation counts in tests. Not auto-required — opt in with:

require "rails_memory_profiler/test_helper"

Works as a module-level call or mixed into a test class via include/extend:

include RailsMemoryProfiler::TestHelper

For RSpec block expectations see rspec_matchers. For Minitest assertions see minitest_matchers.

Instance Method Summary collapse

Instance Method Details

#assert_allocations_below(threshold, &block) ⇒ void

This method returns an undefined value.

Asserts that the block allocates fewer than threshold objects. Raises Minitest::Assertion when Minitest is loaded (so the failure is reported as a test failure rather than an error), otherwise raises RuntimeError.

Parameters:

  • threshold (Integer)

    maximum acceptable allocation count

Yield Returns:

  • (Object)

    the block’s return value is discarded

Raises:

  • (Minitest::Assertion)

    when Minitest is present and the threshold is exceeded

  • (RuntimeError)

    when Minitest is absent and the threshold is exceeded



39
40
41
42
43
44
45
46
# File 'lib/rails_memory_profiler/test_helper.rb', line 39

def assert_allocations_below(threshold, &block)
  count = capture_allocations(&block)
  return if count < threshold

  message = "Expected fewer than #{threshold} allocated objects but got #{count}"
  error_class = Object.const_defined?(:Minitest) ? Minitest::Assertion : RuntimeError
  raise error_class, message
end

#capture_allocationsInteger

Runs the block and returns the number of Ruby objects allocated during it. Triggers a full GC before measuring to reduce noise from prior allocations.

Yield Returns:

  • (Object)

    the block’s return value is discarded

Returns:

  • (Integer)

    number of objects allocated



23
24
25
26
27
28
# File 'lib/rails_memory_profiler/test_helper.rb', line 23

def capture_allocations
  GC.start
  before = GC.stat(:total_allocated_objects)
  yield
  GC.stat(:total_allocated_objects) - before
end