Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stash methods that get and set thread local variables to allow the user to mock them #606

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions lib/rspec/support.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,23 @@ 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
THREAD_VARIABLE_GET = Thread.instance_method(:thread_variable_get)
THREAD_VARIABLE_SET = Thread.instance_method(:thread_variable_set)
else
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.
if RUBY_VERSION >= '2.7'
def self.thread_local_data
Thread.current.thread_variable_get(:__rspec) || Thread.current.thread_variable_set(:__rspec, {})
THREAD_VARIABLE_GET.bind_call(Thread.current, :__rspec) || THREAD_VARIABLE_SET.bind_call(Thread.current, :__rspec, {})
end
else
def self.thread_local_data
Thread.current[:__rspec] ||= {}
THREAD_VARIABLE_GET.bind(Thread.current).call(:__rspec) || THREAD_VARIABLE_SET.bind(Thread.current).call(:__rspec, {})
end
end

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