自定义消息

RSpec 尝试提供有用的失败消息,但对于您想要更具体信息的案例,您可以在示例中直接定义自己的消息。这适用于除操作符匹配器之外的任何匹配器。

自定义失败消息

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

RSpec.describe Array do
  context "when created with `new`" do
    it "is empty" do
      array = Array.new
      array << 1 # trigger a failure to demonstrate the message
      expect(array).to be_empty, "expected empty array, got #{array.inspect}"
    end
  end
end

我运行 rspec example_spec.rb --format documentation

然后输出应该包含“期望为空数组,得到 [1]”。

使用 proc 自定义失败消息

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

RSpec.describe Array do
  context "when created with `new`" do
    it "is empty" do
      array = Array.new
      array << 1 # trigger a failure to demonstrate the message
      expect(array).to be_empty, lambda { "expected empty array, got #{array.inspect}" }
    end
  end
end

我运行 rspec example_spec.rb --format documentation

然后输出应该包含“期望为空数组,得到 [1]”。