RSpec 提供当前范围为 RSpec.current_scope

您可以检测您的辅助方法或库代码正在执行的 rspec 范围。例如,如果您的方法只有在特定上下文中调用才有意义,这将很有用。

检测当前范围

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

# Outside of the test lifecycle, the current scope is `:suite`
exit(1) unless RSpec.current_scope == :suite

at_exit do
  exit(1) unless RSpec.current_scope == :suite
end

RSpec.configure do |c|
  c.before :suite do
    expect(RSpec.current_scope).to eq(:before_suite_hook)
  end

  c.before :context do
    expect(RSpec.current_scope).to eq(:before_context_hook)
  end

  c.before :example do
    expect(RSpec.current_scope).to eq(:before_example_hook)
  end

  c.around :example do |ex|
    expect(RSpec.current_scope).to eq(:before_example_hook)
    ex.run
    expect(RSpec.current_scope).to eq(:after_example_hook)
  end

  c.after :example do
    expect(RSpec.current_scope).to eq(:after_example_hook)
  end

  c.after :context do
    expect(RSpec.current_scope).to eq(:after_context_hook)
  end

  c.after :suite do
    expect(RSpec.current_scope).to eq(:after_suite_hook)
  end
end

RSpec.describe "RSpec.current_scope" do
  before :context do
    expect(RSpec.current_scope).to eq(:before_context_hook)
  end

  before :example do
    expect(RSpec.current_scope).to eq(:before_example_hook)
  end

  around :example do |ex|
    expect(RSpec.current_scope).to eq(:before_example_hook)
    ex.run
    expect(RSpec.current_scope).to eq(:after_example_hook)
  end

  after :example do
    expect(RSpec.current_scope).to eq(:after_example_hook)
  end

  after :context do
    expect(RSpec.current_scope).to eq(:after_context_hook)
  end

  it "is :example in an example" do
    expect(RSpec.current_scope).to eq(:example)
  end

  it "works for multiple examples" do
    expect(RSpec.current_scope).to eq(:example)
  end

  describe "in nested describe blocks" do
    it "still works" do
      expect(RSpec.current_scope).to eq(:example)
    end
  end
end

我运行 rspec current_scope_spec.rb

然后示例应该全部通过。