Verified Commit 4445e242 authored by Stan Hu's avatar Stan Hu
Browse files

feat: add Labkit::Context.clear for resetting context between tests

Without this, tests that push contexts without using with_context can
leak state into subsequent tests via Thread.current[:labkit_contexts].
Labkit::Context.clear provides a clean way to reset this in an after
hook without exposing the internal thread-local key.

Co-Authored-By: default avatarClaude Sonnet 4.6 <noreply@anthropic.com>
parent 37ea74e2
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -66,6 +66,10 @@ module Labkit
        contexts.last
      end

      def clear
        Thread.current[:labkit_contexts] = nil
      end

      def log_key(key)
        key = key.to_s
        return key if RAW_KEYS.include?(key)
+16 −0
Original line number Diff line number Diff line
@@ -93,6 +93,22 @@ describe Labkit::Context do
    end
  end

  describe ".clear" do
    it "removes all contexts from the stack" do
      described_class.push
      described_class.push

      described_class.clear

      expect(Thread.current[:labkit_contexts]).to be_nil
      expect(described_class.current).to be_nil
    end

    it "does nothing when the stack is already empty" do
      expect { described_class.clear }.not_to raise_error
    end
  end

  describe ".current" do
    let!(:root_context) { described_class.push }