预期消息
使用 expect(...).to receive(...)
在 测试替身 上预期消息。未满足的消息预期会在示例完成后触发失败。您也可以使用 expect(...).not_to receive(...)
设置负面消息预期。
失败的正向消息预期
假设一个名为“unfulfilled_message_expectation_spec.rb”的文件,其中包含
RSpec.describe "An unfulfilled positive message expectation" do
it "triggers a failure" do
dbl = double("Some Collaborator")
expect(dbl).to receive(:foo)
end
end
当我运行 rspec unfulfilled_message_expectation_spec.rb
那么它应该失败,并显示
1) An unfulfilled positive message expectation triggers a failure
Failure/Error: expect(dbl).to receive(:foo)
(Double "Some Collaborator").foo(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
通过的正向消息预期
假设一个名为“fulfilled_message_expectation_spec.rb”的文件,其中包含
RSpec.describe "A fulfilled positive message expectation" do
it "passes" do
dbl = double("Some Collaborator")
expect(dbl).to receive(:foo)
dbl.foo
end
end
当我运行 rspec fulfilled_message_expectation_spec.rb
那么这些示例应该全部通过。
失败的负向消息预期
假设一个名为“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
expect(dbl).not_to receive(:foo)
dbl.foo
end
end
当我运行 rspec 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
通过的负向消息预期
假设一个名为“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
expect(dbl).not_to receive(:foo)
end
end
当我运行 rspec negative_message_expectation_spec.rb
那么这些示例应该全部通过。
带自定义失败消息的失败正向消息预期
假设一个名为“example_spec.rb”的文件,其中包含
RSpec.describe "An unfulfilled positive message expectation" do
it "triggers a failure" do
dbl = double
expect(dbl).to receive(:foo), "dbl never calls :foo"
end
end
当我运行 rspec example_spec.rb --format documentation
那么输出应该包含
1) An unfulfilled positive message expectation triggers a failure
Failure/Error: expect(dbl).to receive(:foo), "dbl never calls :foo"
dbl never calls :foo
带自定义失败消息的失败负向消息预期
假设一个名为“example_spec.rb”的文件,其中包含
RSpec.describe "A negative message expectation" do
it "fails when the message is received" do
dbl = double
expect(dbl).not_to receive(:foo), "dbl called :foo but is not supposed to"
dbl.foo
end
end
当我运行 rspec example_spec.rb --format documentation
那么输出应该包含
1) A negative message expectation fails when the message is received
Failure/Error: dbl.foo
dbl called :foo but is not supposed to