【问题标题】:How to stub any instances for a given class using Rspec Mocks如何使用 Rspec Mocks 存根给定类的任何实例
【发布时间】:2011-04-12 19:57:11
【问题描述】:

以下代码引发错误:undefined method 'any_instance' for String:Class

require 'rspec'

RSpec.configure do |config|
  config.mock_with :rspec
end

describe String do
  it 'stubs' do
    String.any_instance.stub(:foo).and_return(1)
    ''.foo.should eq(1)
  end
end

如何将 Mocks 模块包含到 Class 或 Object 类中?

【问题讨论】:

    标签: ruby mocking rspec


    【解决方案1】:

    any_instance 最近被添加到 rspec,所以你的示例现在对我有用,就像 rspec 2.7 一样。

    rspec 3 更新:

    执行此操作的新方法是 allow_any_instance_of(String).to receive(:foo).and_return(1)

    这里有更多 any_instance 文档:https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance

    【解决方案2】:

    使用 2.6.0 之前的版本中的 RSpec Mocks,您无法做到这一点。但是,您可以将 any_instance 与 Mocha 一起使用(如 here 所示)或更高版本的 Rspec。

    在你的spec/spec_helper.rb

    确保你有这一行:

    config.mock_with :mocha

    未注释。

    【讨论】:

    • 好吧,鉴于问题是“使用 Rspec Mocks”,我不确定“不要使用 Rspec Mocks”的答案是否有用。再说一次,这比技术上正确的答案要好:你做不到。
    • 上面的测试其实是来自Rspec本身link的测试。通过 (mocks.rb) 包含模块 AnyInstance:Class.class_eval { include RSpec::Mocks::AnyInstance } 我认为有办法以某种方式做到这一点。
    • 那是当前的master,但还没有发布。它将在接下来的一两周内成为 rspec-mocks-2.6.0 版本的一部分。
    • 我在 2.7.1 但也有类似的问题
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多