使用rspec-mocks的测试模块方法

时间:2014-12-11 13:59:03

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

如何使用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配置应该有配置实例        失败/错误:允许(obj)。接收(:config).and_return(config)          TestModule没有实现:config        #。/ spec / config_spec.rb:41:在&#39;

中的块(2级)

2 个答案:

答案 0 :(得分:1)

我相信你混淆了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

答案 1 :(得分: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方法到TestModule。如果您想允许从外部更改.config,那么只需要attr_writer :config即可,因为读者/获取者已经被定义为该方法。

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

相关问题