返回值

使用 and_return 指定返回值。传递多个 and_return 值以指定连续调用时的不同返回值。如果消息被额外接收,则将继续返回最后一个值。

注意 - 如果您正在寻找有关配置 allow_any_instance_of 响应的文档,请参阅 使用遗留代码 文档。

默认情况下返回 nil

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

RSpec.describe "The default response" do
  it "returns nil when no response has been configured" do
    dbl = double
    allow(dbl).to receive(:foo)
    expect(dbl.foo).to be_nil
  end
end

我运行 rspec returns_nil_spec.rb

那么这些示例应该全部通过。

指定返回值

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

RSpec.describe "Specifying a return value" do
  it "returns the specified return value" do
    dbl = double
    allow(dbl).to receive(:foo).and_return(14)
    expect(dbl.foo).to eq(14)
  end
end

我运行 rspec and_return_spec.rb

那么这些示例应该全部通过。

为多个调用指定不同的返回值

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

RSpec.describe "When the method is called multiple times" do
  it "returns the specified values in order, then keeps returning the last value" do
    dbl = double
    allow(dbl).to receive(:foo).and_return(1, 2, 3)

    expect(dbl.foo).to eq(1)
    expect(dbl.foo).to eq(2)
    expect(dbl.foo).to eq(3)
    expect(dbl.foo).to eq(3) # begins to repeat last value
    expect(dbl.foo).to eq(3)
  end
end

我运行 rspec multiple_calls_spec.rb

那么这些示例应该全部通过。