2013-05-13 16:04:03 +08:00
|
|
|
require 'spec_helper'
|
|
|
|
require 'cache'
|
|
|
|
|
|
|
|
describe Cache do
|
|
|
|
|
|
|
|
let :cache do
|
|
|
|
Cache.new
|
|
|
|
end
|
|
|
|
|
2014-01-07 14:36:47 +08:00
|
|
|
it "supports fixnum" do
|
|
|
|
cache.write("num", 1)
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(cache.read("num")).to eq(1)
|
2014-01-07 14:36:47 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
it "supports hash" do
|
|
|
|
hash = {a: 1, b: [1,2,3]}
|
|
|
|
cache.write("hash", hash)
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(cache.read("hash")).to eq(hash)
|
2014-01-07 14:36:47 +08:00
|
|
|
end
|
|
|
|
|
2014-01-06 13:50:04 +08:00
|
|
|
it "can be cleared" do
|
2015-02-19 13:58:05 +08:00
|
|
|
$redis.set("boo", "boo")
|
2014-01-06 13:50:04 +08:00
|
|
|
cache.write("hello0", "world")
|
|
|
|
cache.write("hello1", "world")
|
|
|
|
cache.clear
|
2013-05-13 16:04:03 +08:00
|
|
|
|
2015-02-19 13:58:05 +08:00
|
|
|
expect($redis.get("boo")).to eq("boo")
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(cache.read("hello0")).to eq(nil)
|
2014-01-06 13:50:04 +08:00
|
|
|
end
|
|
|
|
|
2013-05-13 16:04:03 +08:00
|
|
|
it "can delete correctly" do
|
2014-01-06 13:50:04 +08:00
|
|
|
cache.fetch("key", expires_in: 1.minute) do
|
2013-05-13 16:04:03 +08:00
|
|
|
"test"
|
|
|
|
end
|
|
|
|
|
|
|
|
cache.delete("key")
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(cache.fetch("key")).to eq(nil)
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
2014-01-07 14:36:47 +08:00
|
|
|
it "calls setex in redis" do
|
|
|
|
cache.delete("key")
|
2015-02-19 13:58:05 +08:00
|
|
|
cache.delete("bla")
|
2014-01-07 14:36:47 +08:00
|
|
|
|
2014-01-06 13:50:04 +08:00
|
|
|
key = cache.namespaced_key("key")
|
2013-05-13 16:04:03 +08:00
|
|
|
|
2014-01-07 14:36:47 +08:00
|
|
|
cache.fetch("key", expires_in: 1.minute) do
|
2013-05-13 16:04:03 +08:00
|
|
|
"bob"
|
|
|
|
end
|
2015-02-19 13:58:05 +08:00
|
|
|
|
|
|
|
expect($redis.ttl(key)).to be_within(2.seconds).of(1.minute)
|
|
|
|
|
|
|
|
# we always expire withing a day
|
|
|
|
cache.fetch("bla"){ "hi" }
|
|
|
|
|
|
|
|
key = cache.namespaced_key("bla")
|
|
|
|
expect($redis.ttl(key)).to be_within(2.seconds).of(1.day)
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
it "can store and fetch correctly" do
|
2014-01-07 14:36:47 +08:00
|
|
|
cache.delete "key"
|
2013-05-13 16:04:03 +08:00
|
|
|
|
|
|
|
r = cache.fetch "key" do
|
|
|
|
"bob"
|
|
|
|
end
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(r).to eq("bob")
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
it "can fetch existing correctly" do
|
2014-01-07 14:36:47 +08:00
|
|
|
cache.write "key", "bill"
|
2013-05-13 16:04:03 +08:00
|
|
|
|
|
|
|
r = cache.fetch "key" do
|
|
|
|
"bob"
|
|
|
|
end
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(r).to eq("bill")
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
end
|