【问题标题】:Rspec - stub module methodRspec - 存根模块方法
【发布时间】:2013-08-22 10:21:35
【问题描述】:

如何在模块中存根方法:

module SomeModule
    def method_one
        # do stuff
        something = method_two(some_arg)
        # so more stuff
    end

    def method_two(arg)
        # do stuff
    end
end

我可以单独测试method_two

我也想通过存根method_two 的返回值来单独测试method_one

shared_examples_for SomeModule do
    it 'does something exciting' do
        # neither of the below work
        # SomeModule.should_receive(:method_two).and_return('MANUAL')
        # SomeModule.stub(:method_two).and_return('MANUAL')

        # expect(described_class.new.method_one).to eq(some_value)
    end
end

describe SomeController do
    include_examples SomeModule
end

SomeController 中包含的 SomeModule 中的规范失败,因为 method_two 引发异常(它尝试执行尚未播种的数据库查找)。

当在method_one 中调用method_two 时,如何存根?

【问题讨论】:

  • 您对这个模块有什么期望?成为 mixin 或在类级别从中调用方法,例如:SomeModule.foo ?
  • 振作起来,乔治。在我看来,对问题投反对票通常是个坏主意,但好消息是,不恰当的问题经常会引发反补贴的投反对票,从而为您带来净代表胜利,而不会产生净选票影响。
  • 除了@apneadving 的问题外,不清楚您要测试的代码中模块与控制器的关系是什么。另外,我不清楚将类名传递给 shared_examples_for 的作用,因为我只在文档中看到一个字符串用作参数作为调用它的一种方式。
  • 无论如何,如果您的控制器混合在该模块中,您需要存根控制器实例方法,而不是您尝试做的模块类方法。

标签: ruby-on-rails rspec mocking


【解决方案1】:
shared_examples_for SomeModule do
  let(:instance) { described_class.new }

  it 'does something exciting' do
    instance.should_receive(:method_two).and_return('MANUAL')
    expect(instance.method_one).to eq(some_value)
  end
end

describe SomeController do
  include_examples SomeModule
end

【讨论】:

  • 请尝试对正在发生的事情以及您背后的原因进行一些解释。
【解决方案2】:
allow_any_instance_of(M).to receive(:foo).and_return(:bar)

Is there a way to stub a method of an included module with Rspec?

这种方法适合我

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2012-06-13
    • 2013-01-10
    相关资源
    最近更新 更多