Skip to content

Context example

Cyril Kato edited this page Nov 1, 2026 · 1 revision

A context runs its specs in a child process, forked from the one that loads the file: a constant, a global or any other change made inside stays in the child, and the parent exits with the status 1 when the child did not succeed. A describe runs in the process itself.

require "r_spec"

RSpec.describe "a context" do
  context "when it defines a constant" do
    ANSWER = 42

    it { expect(ANSWER).to be 42 }
  end

  context "when it sets a global" do
    before { $counter = 1 }

    it { expect($counter).to be 1 }
  end

  it "sees none of it" do
    expect(defined?(ANSWER)).to be_nil
    expect($counter).to be_nil
  end
end
$ ruby spec/context_spec.rb
spec/context_spec.rb:7: Success: expected 42 to be 42
spec/context_spec.rb:13: Success: expected 1 to be 1
spec/context_spec.rb:17: Success: expected nil to be nil
spec/context_spec.rb:18: Success: expected nil to be nil

The same isolation protects the next context from what the subject of this one leaves behind: an object mutated by a test, a monkey patch, a changed current directory.

Clone this wiki locally