any_instance

any_instance 是模拟任何类实例的旧方法,但它带有对所有类的全局猴子补丁的负担。请注意,我们通常不建议使用此功能。

背景

给定一个名为“spec/spec_helper.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec do |mocks|
    mocks.syntax = :should
  end
end

以及一个名为“.rspec”的文件,其中包含

--require spec_helper

模拟类任何实例上的方法

给定一个名为“spec/example_spec.rb”的文件,其中包含

RSpec.describe "Stubbing a method with any_instance" do
  it "returns the specified value on any instance of the class" do
    Object.any_instance.stub(:foo).and_return(:return_value)

    o = Object.new
    expect(o.foo).to eq(:return_value)
  end
end

我运行rspec spec/example_spec.rb

那么示例应该全部通过。

模拟类任何实例上的多个方法

给定一个名为“spec/example_spec.rb”的文件,其中包含

RSpec.describe "Stubbing multiple methods with any_instance" do
  it "returns the specified values for the given messages" do
    Object.any_instance.stub(:foo => 'foo', :bar => 'bar')

    o = Object.new
    expect(o.foo).to eq('foo')
    expect(o.bar).to eq('bar')
  end
end

我运行rspec spec/example_spec.rb

那么示例应该全部通过。

使用特定参数模拟类任何实例

给定一个名为“spec/example_spec.rb”的文件,其中包含

RSpec.describe "Stubbing any instance with arguments" do
  it "returns the stubbed value when arguments match" do
    Object.any_instance.stub(:foo).with(:param_one, :param_two).and_return(:result_one)
    Object.any_instance.stub(:foo).with(:param_three, :param_four).and_return(:result_two)

    o = Object.new
    expect(o.foo(:param_one, :param_two)).to eq(:result_one)
    expect(o.foo(:param_three, :param_four)).to eq(:result_two)
  end
end

我运行rspec spec/example_spec.rb

那么示例应该全部通过。

块实现将接收器作为第一个参数传递

给定一个名为“spec/example_spec.rb”的文件,其中包含

RSpec.describe "Stubbing any instance of a class" do
  it 'yields the receiver to the block implementation' do
    String.any_instance.stub(:slice) do |value, start, length|
      value[start, length]
    end

    expect('string'.slice(2, 3)).to eq('rin')
  end
end

我运行rspec spec/example_spec.rb

那么示例应该全部通过。

预期类任何实例上的消息

给定一个名为“spec/example_spec.rb”的文件,其中包含

RSpec.describe "Expecting a message on any instance of a class" do
  before do
    Object.any_instance.should_receive(:foo)
  end

  it "passes when an instance receives the message" do
    Object.new.foo
  end

  it "fails when no instance receives the message" do
    Object.new.to_s
  end
end

我运行rspec spec/example_spec.rb

那么它应该失败,并显示以下输出

2 个示例,1 个失败
正好应该有一个实例收到以下消息,但没有收到:foo