如何使用RSpec测试记忆?

bac*_*rhh 4 ruby ruby-on-rails memoization rspec2 rspec-rails

我的其中一个课程中有下一个代码:

class Settings < ActiveRecord::Base
  def self.current
    @settings ||= Settings.where({ environment: Rails.env }).first_or_create!
  end
  # Other methods
end
Run Code Online (Sandbox Code Playgroud)

基本行为:

  1. 它会在第一次通话时创建新记录.
  2. 它随后的调用返回相同的结果.
  3. 它会在每次更新后重置ivar,并在后续调用中返回与当前环境关联的第一个(也是唯一的)记录.

对于这种方法,我有下一个测试:

describe Settings do
  describe ".current" do
    it "gets all settings for current environment" do
      expect(Settings.current).to eq(Settings.where({ environment: 'test' }).first)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我对此感到不舒服,因为我实际上并没有测试memoization,所以我一直在关注这个问题的方法,我尝试过类似的东西:

describe ".current" do
  it "gets all settings for current environment" do
    expect(Settings).to receive(:where).with({ environment: 'test' }).once
    2.times { Settings.current }
  end
end
Run Code Online (Sandbox Code Playgroud)

但是此测试返回以下错误:

NoMethodError:
  undefined method `first_or_create!' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如何使用RSpec测试此方法的memoization?

更新:

最后,我的方法如下:

describe Settings do
  describe ".current" do
    it "gets all settings for current environment" do
      expect(described_class.current).to eq(described_class.where(environment: 'test').first)
    end
    it "memoizes the settings for current environment in subsequent calls" do
      expect(described_class).to receive(:where).once.with(environment: 'test').and_call_original
      2.times { described_class.current }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Ash*_*son 7

添加.and_call_original到您的邮件期望:

expect(Settings).to receive(:where).with({ environment: 'test' }).once.and_call_original
Run Code Online (Sandbox Code Playgroud)