开发者

How to stub any instances for a given class using Rspec Mocks

T开发者_StackOverflow中文版he following code raises an error: 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

How can I include the Mocks module into the Class or Object class?


any_instance was recently added to rspec, so your example now works for me as it is with rspec 2.7.

Update for rspec 3:

The new way to do this is allow_any_instance_of(String).to receive(:foo).and_return(1)

Here is more any_instance documentation: https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance


With RSpec Mocks in versions previous to 2.6.0, you cannot do it. However you can use any_instance with Mocha(as seen here) or in later versions of Rspec.

In your spec/spec_helper.rb

Make sure you have this line:

config.mock_with :mocha

uncommented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜