BUGFIX: UserStat spec was over ambitious with its mocking

This commit is contained in:
Sam 2014-01-06 16:50:55 +11:00
parent b703d8c77a
commit 6befdceabf
2 changed files with 19 additions and 7 deletions

View File

@ -55,15 +55,27 @@ class UserStat < ActiveRecord::Base
MAX_TIME_READ_DIFF = 100 MAX_TIME_READ_DIFF = 100
# attempt to add total read time to user based on previous time this was called # attempt to add total read time to user based on previous time this was called
def update_time_read! def update_time_read!
last_seen_key = "user-last-seen:#{id}" if last_seen = last_seen_cached
last_seen = $redis.get(last_seen_key)
if last_seen.present?
diff = (Time.now.to_f - last_seen.to_f).round diff = (Time.now.to_f - last_seen.to_f).round
if diff > 0 && diff < MAX_TIME_READ_DIFF if diff > 0 && diff < MAX_TIME_READ_DIFF
UserStat.where(user_id: id, time_read: time_read).update_all ["time_read = time_read + ?", diff] UserStat.where(user_id: id, time_read: time_read).update_all ["time_read = time_read + ?", diff]
end end
end end
$redis.set(last_seen_key, Time.now.to_f) cache_last_seen(Time.now.to_f)
end
private
def last_seen_key
@last_seen_key ||= "user-last-seen:#{id}"
end
def last_seen_cached
$redis.get(last_seen_key)
end
def cache_last_seen(val)
$redis.set(last_seen_key, val)
end end
end end

View File

@ -77,14 +77,14 @@ describe UserStat do
let(:stat) { user.user_stat } let(:stat) { user.user_stat }
it 'makes no changes if nothing is cached' do it 'makes no changes if nothing is cached' do
$redis.expects(:get).with("user-last-seen:#{user.id}").returns(nil) stat.expects(:last_seen_cached).returns(nil)
stat.update_time_read! stat.update_time_read!
stat.reload stat.reload
stat.time_read.should == 0 stat.time_read.should == 0
end end
it 'makes a change if time read is below threshold' do it 'makes a change if time read is below threshold' do
$redis.expects(:get).with("user-last-seen:#{user.id}").returns(Time.now - 10.0) stat.expects(:last_seen_cached).returns(Time.now - 10)
stat.update_time_read! stat.update_time_read!
stat.reload stat.reload
stat.time_read.should == 10 stat.time_read.should == 10
@ -92,7 +92,7 @@ describe UserStat do
it 'makes no change if time read is above threshold' do it 'makes no change if time read is above threshold' do
t = Time.now - 1 - UserStat::MAX_TIME_READ_DIFF t = Time.now - 1 - UserStat::MAX_TIME_READ_DIFF
$redis.expects(:get).with("user-last-seen:#{user.id}").returns(t) stat.expects(:last_seen_cached).returns(t)
stat.update_time_read! stat.update_time_read!
stat.reload stat.reload
stat.time_read.should == 0 stat.time_read.should == 0