stub

stub允许消息 的旧方法,但它在所有对象上都带有全局猴子补丁的负担。它支持相同的流畅接口用于 设置约束配置响应。您还可以将 stub 传递一个消息/返回值对的哈希表,它类似于 allow(obj).to receive_messages(hash),但不支持通过流畅接口进行进一步自定义。

背景

假设一个名为“spec/spec_helper.rb”的文件,内容如下

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

并且一个名为“.rspec”的文件,内容如下

--require spec_helper

模拟一个方法

假设一个名为“spec/stub_spec.rb”的文件,内容如下

RSpec.describe "Stubbing a method" do
  it "configures how the object responds" do
    dbl = double
    dbl.stub(:foo).and_return(13)
    expect(dbl.foo).to eq(13)
  end
end

我运行 rspec spec/stub_spec.rb

所有示例都应该通过。

通过传递一个哈希表模拟多个方法

假设一个名为“spec/stub_multiple_methods_spec.rb”的文件,内容如下

RSpec.describe "Stubbing multiple methods" do
  it "stubs each named method with the given return value" do
    dbl = double
    dbl.stub(:foo => 13, :bar => 10)
    expect(dbl.foo).to eq(13)
    expect(dbl.bar).to eq(10)
  end
end

我运行 rspec spec/stub_multiple_methods_spec.rb

所有示例都应该通过。