【问题标题】:Test module method with rspec-mocks使用 rspec-mocks 测试模块方法
【发布时间】:2014-12-11 13:59:03
【问题描述】:

如何使用 Rspec 3 模拟测试此模块中的配置方法?

module TestModule
  class << self
    attr_accessor :config
  end
  def self.config
    @config ||= Config.new
  end
  class Config
    attr_accessor :money_url
    def initialize
      @money_url = "https://example1.come"
    end
  end
end

我尝试过这样的事情:

describe "TestModule config" do
  it "should have config instance" do
    config = class_double("TestModule::Config")
    obj = instance_double("TestModule")
    allow(obj).to receive(:config).and_return(config)
    obj.config
    expect(obj.config).to eq(config)
  end
end

看起来,它不起作用,为什么?

失败:

1) TestModule 配置应该有配置实例 失败/错误:allow(obj).to receive(:config).and_return(config) TestModule 未实现:config # ./spec/config_spec.rb:41:in `block (2 levels) in '

【问题讨论】:

    标签: ruby unit-testing rspec mocking rspec-mocks


    【解决方案1】:

    我建议直接使用

    测试该类
    describe "module config" do
      it "has config" do
        expect(TestModule.config).to be kind_of(TestModule::Config)
      end
    end
    

    如果您不需要外部对象更改 .config,则无需使用 attr_accessor :config,因为 def self.config 已经为 .config 定义了可访问的 .config 方法TestModule。如果您想允许从外部更改 .config,那么只需使用 attr_writer :config 就足够了,因为 reader/getter 已经定义为该方法。

    此外,如果您已经使用class &lt;&lt; self 打开了您的类,那么在其中声明.config 方法会更有意义,因为它将包含所有类级别的定义。只需从声明的开头删除self.,使其变为def config,因为您已经“在”类中。

    【讨论】:

    • 对不起,我希望你不要认为我偷了你的答案。您在我更新原始回复的过程中提交了此内容。不过,我认为我们都同意解决方案。 :)
    • 感谢详细解答!
    【解决方案2】:

    我相信您混淆了 class_double 和 instance_double。尝试切换它们,看看效果如何。 (手机发的,请见谅)

    更新:现在我在电脑前,我可以深入研究一下。首先,你为什么要存根你正在测试的方法?您不是要测试它是否返回Config 类的实例吗?通过存根.config 方法,您并没有真正测试您的方法以证明它可以执行您希望它执行的操作。我认为您真的可以将其简化为:

    RSpec.describe TestModule do
      describe ".config" do
        it "returns an Config instance" do
          expect(TestModule.config).to be_a TestModule::Config
        end
      end
    end
    

    【讨论】:

    • 另外,TestModule 不是对象实例,因此您的测试在编写方式上有点混乱。
    • 感谢您的精彩回答!
    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多