Timecop-时间片度测试
class CourseSign < ActiveRecord::Base
attr_accessible :course_id, :user_id, :streak
belongs_to :user
belongs_to :course
validates :user, :presence => true
validates :course, :presence => true
validates :user_id, :uniqueness => {:scope => :course_id}
scope :current_signs, lambda {|course,date|{:conditions =>
['course_id=? AND DATE(created_at)=?', course.id, Date.today]
}}
scope :current_signs_for_user, lambda {|course,date,user|
current_signs(course,date).where(:user_id => user.id)
}
end
module CourseSignModule
# 2 课程模型上需要封装用户进行签到的方法
def sign(user)
return if !current_sign_for_user(user,Date.today).blank?
CourseSign.create(:course_id => self.id, :user_id => user.id, :streak => current_streak_for(user) )
end
# 截至今天的连续签到天数
def current_streak_for(user)
@yesterday = current_sign_for_user(user,Date.today-1)
return 1 if @yesterday.blank?
@yesterday.streak + 1
end
def current_sign_for_user(user,date)
CourseSign.current_signs_for_user(self,date,user).first
end
# 3 课程模型上需要封装获取总签到数的查询方法
def signs_count
CourseSign.where(:course_id => self.id).count
end
# 4 课程模型上需要封装某个用户今天是第几个签到的查询方法
def sign_number(user)
@course_sign = current_sign_for_user(user, Date.today)
index = current_signs.index(@course_sign)
index && index + 1
end
def current_signs
CourseSign.current_signs(self,Date.today).order('id asc')
end
# 6 课程模型上需要封装获取当天签到人数的查询方法
def current_signs_count
current_signs.size
end
end
require "spec_helper"
describe Course do
context '签到模块' do
before do
@user = FactoryGirl.create(:user)
@course = FactoryGirl.create(:course)
end
describe '#sign' do
it{expect {@course.sign(@user)}.to change {CourseSign.count}.by(1)}
end
describe '#current_streak_for' do
context '昨天没有签到' do
it {@course.current_streak_for(@user) == 1}
end
context '昨天前天连续签到了' do
before do
Timecop.travel(Date.today - 2)
@course.sign(@user)
Timecop.travel(Date.today - 1)
@course.sign(@user)
end
it {@course.current_streak_for(@user) == 3}
end
end
describe '#signs_count' do
let(:user1) {FactoryGirl.create :user}
let(:user2) {FactoryGirl.create :user}
let(:user3) {FactoryGirl.create :user}
let(:course2) {FactoryGirl.create :course}
before do
course2.sign(user1)
@course.sign(user1)
@course.sign(user2)
@course.sign(user3)
end
it{ @course.signs_count == 3 }
it{ course2.signs_count == 1 }
end
describe '#sign_number' do
let(:user1) {FactoryGirl.create :user}
let(:user2) {FactoryGirl.create :user}
before do
@course.sign(user1)
@course.sign(user2)
end
it{ @course.sign_number(user2) == 2}
end
describe '#current_signs_count' do
let(:user1) {FactoryGirl.create :user}
let(:user2) {FactoryGirl.create :user}
let(:user3) {FactoryGirl.create :user}
let(:course2) {FactoryGirl.create :course}
before do
course2.sign(user1)
@course.sign(user1)
@course.sign(user2)
@course.sign(user3)
end
it {@course.current_signs_count.should == 3}
end
end
end
补充:综合编程 , 其他综合 ,