微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Rspec – 存根模块方法

如何在模块中存根方法
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.

我想通过stubbing 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中包含的规范失败,因为method_two抛出一个异常(它尝试做一个未被种子的数据库查找).

在method_one中调用的时候如何存根method_two?

解决方法

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

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

相关推荐