如何使用 gem `memory_profiler` 用法编写单元测试?

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

例如,我们有class实现:

class Memory
  def call
   2 * 2
  end
end

我们可以通过memory_profiler 用法获取报告:

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

当我们有内存增加或内存泄漏时失败的单元测试如何实现 Memory#call?

例如,如果我们要以这种方式更改 Memory#call

- 2 * 2
+ loop { 2 * 2 }

我认为你不应该把它作为单元测试,因为测试环境有点不同它不应该知道代码的时间成本或内存成本,它不应该验证指标,它是工作其他工具。

对于你的情况,我建议编写一些模块,你可以在其中断言分配的内存对你来说没问题,例如你可以做一些事情

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