discourse/spec/lib/distributed_memoizer_spec.rb
David Taylor c9dab6fd08
DEV: Automatically require 'rails_helper' in all specs (#16077)
It's very easy to forget to add `require 'rails_helper'` at the top of every core/plugin spec file, and omissions can cause some very confusing/sporadic errors.

By setting this flag in `.rspec`, we can remove the need for `require 'rails_helper'` entirely.
2022-03-01 17:50:50 +00:00

55 lines
1.0 KiB
Ruby

# frozen_string_literal: true
describe DistributedMemoizer do
before do
Discourse.redis.del(DistributedMemoizer.redis_key("hello"))
Discourse.redis.del(DistributedMemoizer.redis_lock_key("hello"))
Discourse.redis.unwatch
end
# NOTE we could use a mock redis here, but I think it makes sense to test the real thing
# let(:mock_redis) { MockRedis.new }
def memoize(&block)
DistributedMemoizer.memoize("hello", duration = 120, &block)
end
it "returns the value of a block" do
expect(memoize do
"abc"
end).to eq("abc")
end
it "return the old value once memoized" do
memoize do
"abc"
end
expect(memoize do
"world"
end).to eq("abc")
end
it "memoizes correctly when used concurrently" do
results = []
threads = []
5.times do
threads << Thread.new do
results << memoize do
sleep 0.001
SecureRandom.hex
end
end
end
threads.each(&:join)
expect(results.uniq.length).to eq(1)
expect(results.count).to eq(5)
end
end