Skip to content

Commit

Permalink
Stash methods that get and set thread local variables to allow the us…
Browse files Browse the repository at this point in the history
…er to mock them

Fixes rspec#605.
  • Loading branch information
manueljacob committed Jul 14, 2024
1 parent 42b18c4 commit 444a160
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
17 changes: 10 additions & 7 deletions lib/rspec/support.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,18 @@ def self.class_of(object)
singleton_class.ancestors.find { |ancestor| !ancestor.equal?(singleton_class) }
end

# A single thread local variable so we don't excessively pollute that namespace.
# Stash original methods to allow the user to mock them.
if RUBY_VERSION.to_f >= 2
def self.thread_local_data
Thread.current.thread_variable_get(:__rspec) || Thread.current.thread_variable_set(:__rspec, {})
end
THREAD_VARIABLE_GET = Thread.instance_method(:thread_variable_get)
THREAD_VARIABLE_SET = Thread.instance_method(:thread_variable_set)
else
def self.thread_local_data
Thread.current[:__rspec] ||= {}
end
THREAD_VARIABLE_GET = Thread.instance_method(:[])
THREAD_VARIABLE_SET = Thread.instance_method(:[]=)
end

# A single thread local variable so we don't excessively pollute that namespace.
def self.thread_local_data
THREAD_VARIABLE_GET.bind(Thread.current).call(:__rspec) || THREAD_VARIABLE_SET.bind(Thread.current).call(:__rspec, {})
end

# @api private
Expand Down
11 changes: 11 additions & 0 deletions spec/rspec/support_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 444a160

Please sign in to comment.