从文件中读取命令行配置选项

RSpec 从几个不同的文件中读取命令行配置选项,所有这些文件都符合特定的特异性级别。更高特异性的选项将覆盖来自更低特异性文件的冲突选项。

这些位置是

* **Global options:** First file from the following list (i.e. the user's
  personal global options)

  * `$XDG_CONFIG_HOME/rspec/options` ([XDG Base Directory
    Specification](https://specifications.freedesktop.org/basedir-spec/latest/)
    config)
  * `~/.rspec`

* **Project options:**  `./.rspec` (i.e. in the project's root directory, usually
  checked into the project)

* **Local:** `./.rspec-local` (i.e. in the project's root directory, can be
  gitignored)

在命令行中指定的选项具有更高的特异性,`SPEC_OPTS` 环境变量也是如此。这意味着命令行选项将覆盖项目特定选项,而项目特定选项会覆盖该选项的全局值。

可以使用 `--options` 命令行参数忽略所有默认选项文件,该参数选择一个自定义文件来加载选项。

在 `.rspec` 中设置的颜色

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

--force-color

以及一个名为 “spec/example_spec.rb” 的文件,其中包含

RSpec.describe "color_enabled?" do
  context "when set with RSpec.configure" do
    it "is true" do
      expect(RSpec.configuration).to be_color_enabled
    end
  end
end

当我运行 `rspec ./spec/example_spec.rb` 时

所有示例都应通过。

自定义选项文件

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

--format documentation

以及一个名为 “spec/example_spec.rb” 的文件,其中包含

RSpec.describe "formatter set in custom options file" do
  it "sets formatter" do
    expect(RSpec.configuration.formatters.first).
      to be_a(RSpec::Core::Formatters::DocumentationFormatter)
  end
end

当我运行 `rspec spec/example_spec.rb --options my.options` 时

所有示例都应通过。

RSpec 忽略 `./.rspec`,因为使用了自定义选项文件

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

--format documentation

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

--no-color

以及一个名为 “spec/example_spec.rb” 的文件,其中包含

RSpec.describe "custom options file" do
  it "causes .rspec to be ignored" do
    expect(RSpec.configuration.color_mode).to eq(:automatic)
  end
end

当我运行 `rspec spec/example_spec.rb --options my.options` 时

所有示例都应通过。

在 `.rspec` 中使用 ERB

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

--format <%= true ? 'documentation' : 'progress' %>

以及一个名为 “spec/example_spec.rb” 的文件,其中包含

RSpec.describe "formatter" do
  it "is set to documentation" do
    expect(RSpec.configuration.formatters.first).
      to be_an(RSpec::Core::Formatters::DocumentationFormatter)
  end
end

当我运行 `rspec ./spec/example_spec.rb` 时

所有示例都应通过。