我的其中一个课程中有下一个代码:
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
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。