加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何使用RSpec测试memoization?

发布时间:2020-12-17 02:46:38 所属栏目:百科 来源:网络整理
导读:我的其中一个课程中有下一个代码: class Settings ActiveRecord::Base def self.current @settings ||= Settings.where({ environment: Rails.env }).first_or_create! end # Other methodsend 基本行为: 它在第一次通话时创建新记录. 它随后的调用返回相
我的其中一个课程中有下一个代码:

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

基本行为:

>它在第一次通话时创建新记录.
>它随后的调用返回相同的结果.
>它在每次更新后重置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

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

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

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

NoMethodError:
  undefined method `first_or_create!' for nil:NilClass

所以我的问题是,如何使用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

解决方法

在您的邮件期望中添加.and_call_original:

expect(Settings).to receive(:where).with({ environment: 'test' }).once.and_call_original

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读