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
-
#assert_allocations_below(threshold, &block) ⇒ void
Asserts that the block allocates fewer than
thresholdobjects. -
#capture_allocations ⇒ Integer
Runs the block and returns the number of Ruby objects allocated during it.
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.
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 = "Expected fewer than #{threshold} allocated objects but got #{count}" error_class = Object.const_defined?(:Minitest) ? Minitest::Assertion : RuntimeError raise error_class, end |
#capture_allocations ⇒ Integer
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.
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 |