单行语法

RSpec 支持对subject 设置期望的单行语法。RSpec 将为示例提供一个文档字符串,该字符串是从示例中使用的匹配器自动生成的。这专门设计用于帮助避免在文档字符串和示例中使用的匹配器完全镜像的情况下的重复。如果过度使用,它可能会产生难以阅读或有助于理解您要描述的对象的文档输出。

这有两种形式

* `is_expected` is defined simply as `expect(subject)` and is designed for
  when you are using rspec-expectations with its newer expect-based syntax.
* `should` was designed back when rspec-expectations only had a should-based
  syntax. However, it continues to be available and work even if the
  `:should` syntax is disabled (since that merely removes `Object#should`
  but this is `RSpec::Core::ExampleGroup#should`).

笔记

* This feature is only available when using rspec-expectations.
* Examples defined using this one-liner syntax cannot be directly selected from the command line using the [`--example` option](../command-line/example-option).
* The one-liner syntax only works with non-block expectations (e.g. `expect(obj).to eq`, etc) and it cannot be used with block expectations (e.g. `expect { object }`).

隐式主题

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

RSpec.describe Array do
  describe "when first created" do
    # Rather than:
    # it "should be empty" do
    #   subject.should be_empty
    # end

    it { should be_empty }
    # or
    it { is_expected.to be_empty }
  end
end

我运行rspec example_spec.rb --format doc

然后示例应该全部通过

并且输出应包含

Array
  when first created
    is expected to be empty
    is expected to be empty

显式主题

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

RSpec.describe Array do
  describe "with 3 items" do
    subject { [1,2,3] }
    it { should_not be_empty }
    # or
    it { is_expected.not_to be_empty }
  end
end

我运行rspec example_spec.rb --format doc

然后示例应该全部通过

并且输出应包含

Array
  with 3 items
    is expected not to be empty
    is expected not to be empty