should_receive

should_receive期望消息 的旧方法,但它会对所有对象进行全局猴子补丁,并带来一些负担。它支持用于 设置约束配置响应 的相同流畅接口。

类似地,你可以使用 should_not_receive 来设置一个负面消息期望。

背景

假设 一个名为“spec/spec_helper.rb”的文件,其中包含:

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

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

--require spec_helper

正向消息期望失败

假设 一个名为“spec/unfulfilled_message_expectation_spec.rb”的文件,其中包含:

RSpec.describe "An unfulfilled message expectation" do
  it "triggers a failure" do
    dbl = double("Some Collaborator")
    dbl.should_receive(:foo)
  end
end

我运行 rspec spec/unfulfilled_message_expectation_spec.rb

那么 它应该失败并显示:

  1) An unfulfilled message expectation triggers a failure
     Failure/Error: dbl.should_receive(:foo)

       (Double "Some Collaborator").foo(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

正向消息期望通过

假设 一个名为“spec/fulfilled_message_expectation_spec.rb”的文件,其中包含:

RSpec.describe "A fulfilled message expectation" do
  it "passes" do
    dbl = double("Some Collaborator")
    dbl.should_receive(:foo)
    dbl.foo
  end
end

我运行 rspec spec/fulfilled_message_expectation_spec.rb

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

负向消息期望失败

假设 一个名为“spec/negative_message_expectation_spec.rb”的文件,其中包含:

RSpec.describe "A negative message expectation" do
  it "fails when the message is received" do
    dbl = double("Some Collaborator").as_null_object
    dbl.should_not_receive(:foo)
    dbl.foo
  end
end

我运行 rspec spec/negative_message_expectation_spec.rb

那么 它应该失败并显示:

  1) A negative message expectation fails when the message is received
     Failure/Error: dbl.foo

       (Double "Some Collaborator").foo(no args)
           expected: 0 times with any arguments
           received: 1 time

负向消息期望通过

假设 一个名为“spec/negative_message_expectation_spec.rb”的文件,其中包含:

RSpec.describe "A negative message expectation" do
  it "passes if the message is never received" do
    dbl = double("Some Collaborator").as_null_object
    dbl.should_not_receive(:foo)
  end
end

我运行 rspec spec/negative_message_expectation_spec.rb

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