How to write unit tests with gem `memory_profiler` usage?

Viewed 85

For example, we have class implementation:

class Memory
  def call
   2 * 2
  end
end

we can get report by memory_profiler usage:

require 'memory_profiler'
MemoryProfiler.report{ Memory.new.call  }.pretty_print

How to implement the unit test for this which became failed when we have an increase of memory or memory leak in addition changes into Memory#call?

For example, if we going to change Memory#call in this way:

- 2 * 2
+ loop { 2 * 2 }
1 Answers

I don't think you should place it as unit tests, cause testing is a bit different environment it should not be aware of time cost or memory cost for your code, it should not verify metrics, it is job for other tools.

For your case I would advice to write some module, where you can assert that allocated memory is ok for you, for example you can do something

module MyMemsizeNotifier
  extend self
  ALLOWED_MEMSIZE = 0..4640

  # Or you can receive block, lambdas, procs
  # I will leave it for you implementation
  def call(klass) 
    report = MemoryProfiler.report
      klass.new.call
    end

    exceeds_limit?(report.total_allocated_memsize)
    report
  end

  def exceeds_limit?(total_usage)
    return if ALLOWED_MEMSIZE.include?(total_usage)

    # notify in rollbar, write a log to stdout or to file or any other way to notify
  end
end

## Usage

class MyController
  def index
    ...
    MyMemsizeNotifier.call(Memory)
    ...
  end
end
Related