From 1a69d228d5e61d00c48dba937bd060cddf4e37ca Mon Sep 17 00:00:00 2001 From: Jon Rowe Date: Wed, 17 Jul 2024 11:39:07 +0100 Subject: [PATCH] Switch rspec local data to a thread accessor --- lib/rspec/support.rb | 14 ++++++-------- spec/rspec/support_spec.rb | 11 +++++++++++ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/lib/rspec/support.rb b/lib/rspec/support.rb index 72154e07..36325570 100644 --- a/lib/rspec/support.rb +++ b/lib/rspec/support.rb @@ -1,5 +1,9 @@ # frozen_string_literal: true +class Thread + attr_accessor :__rspec_local_data +end + module RSpec module Support # @api private @@ -91,14 +95,8 @@ def self.class_of(object) end # A single thread local variable so we don't excessively pollute that namespace. - if RUBY_VERSION.to_f >= 2 - def self.thread_local_data - Thread.current.thread_variable_get(:__rspec) || Thread.current.thread_variable_set(:__rspec, {}) - end - else - def self.thread_local_data - Thread.current[:__rspec] ||= {} - end + def self.thread_local_data + Thread.current.__rspec_local_data ||= {} end # @api private diff --git a/spec/rspec/support_spec.rb b/spec/rspec/support_spec.rb index 997658b1..8321c002 100644 --- a/spec/rspec/support_spec.rb +++ b/spec/rspec/support_spec.rb @@ -204,6 +204,17 @@ def object.some_method end.resume end end + + it "works when Thread#thread_variable_get and Thread#thread_variable_set are mocked" do + expect(Thread.current).to receive(:thread_variable_set).with(:test, true).once.and_return(true) + expect(Thread.current).to receive(:thread_variable_get).with(:test).once.and_return(true) + + Thread.current.thread_variable_set(:test, true) + expect(Thread.current.thread_variable_get(:test)).to eq true + + RSpec::Support.thread_local_data[:__for_test] = :oh_hai + expect(RSpec::Support.thread_local_data[:__for_test]).to eq :oh_hai + end end describe "failure notification" do