discourse/spec/components/distributed_memoizer_spec.rb

56 lines
1.1 KiB
Ruby
Raw Normal View History

2016-04-01 05:33:25 +08:00
require 'rails_helper'
require_dependency 'distributed_memoizer'
describe DistributedMemoizer do
before do
$redis.del(DistributedMemoizer.redis_key("hello"))
$redis.del(DistributedMemoizer.redis_lock_key("hello"))
$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
2015-01-10 00:34:37 +08:00
expect(memoize do
"abc"
2015-01-10 00:34:37 +08:00
end).to eq("abc")
end
it "return the old value once memoized" do
memoize do
"abc"
end
2015-01-10 00:34:37 +08:00
expect(memoize do
"world"
2015-01-10 00:34:37 +08:00
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)
2015-01-10 00:34:37 +08:00
expect(results.uniq.length).to eq(1)
expect(results.count).to eq(5)
end
end