全局命名空间 DSL

RSpec 有几个顶级结构,允许您开始描述行为

历史上,这些结构直接在主对象上可用,因此您可以在文件开头使用它们,而无需 RSpec. 前缀。它们也可以在任何类或模块上使用,以便您可以在特定常量命名空间内对示例进行作用域。

RSpec 3 现在提供了一个选项来禁用此全局猴子修补

  config.expose_dsl_globally = false

为了向后兼容性,它默认为 true

默认情况下,RSpec 允许在全局范围内使用 DSL

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

describe "specs here" do
  it "passes" do
  end
end

我运行 rspec

那么输出应包含“1 个示例,0 个失败”。

默认情况下,rspec/autorun 允许在全局范围内使用 DSL

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

require 'rspec/autorun'
describe "specs here" do
  it "passes" do
  end
end

我运行 ruby spec/example_spec.rb

那么输出应包含“1 个示例,0 个失败”。

当全局暴露被禁用时,顶级 DSL 将不再工作

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

RSpec.configure { |c| c.expose_dsl_globally = false }
describe "specs here" do
  it "passes" do
  end
end

我运行 rspec

那么输出应包含 %R{undefined method (`|‘)describe’}。

无论设置如何

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

RSpec.configure { |c| c.expose_dsl_globally = true }
RSpec.describe "specs here" do
  it "passes" do
  end
end

我运行 rspec

那么输出应包含“1 个示例,0 个失败”。