我的rails应用程序涵盖了许多测试。所有测试都在常规情况下通过。也就是说,排除在深夜的时候。
实际上有一些测试在晚上结束时失败了。所有这些测试都涉及修改模型的时间属性,并查看相关模型是否受到影响。
test "changing time should affect hours" do
// ..User is loaded.
user.attend(event)
assert_equal 1, user.hours // User attends a 1 hour event that has passed.
// Move event to the future.
event.update_attributes(date: Date.today,
start_time: Time.now,
end_time: Time.now + 1.hour)
assert_equal 0, attendance_of(user).hours // Passes in day, fails during night
end
test "valid event creation" do
// Count does NOT change by 1 at night.
assert_difference '@group.events.count', 1 do
post group_events_path(@group), event: { ...
date: Date.today,
start_time: Time.now,
end_time: Time.now + 1.hour,
... }
end
end
这里发生了什么?作为参考,这里是我目前用来确定何时更新出勤(这是事件具有的东西)的内容。这来自事件控制器:
def not_ended?
date.future? || (date.today? &&
(Time.now.seconds_since_midnight < end_time.seconds_since_midnight))
end
def update_attendances
// ... Determine the new date, start, and end time values through ActiveRecord::Dirty
if not_ended?
remove_checks = true
end
attendances.each do |attendance|
new_checked = remove_checks ? false : attendance.checked
attendance.update_attributes(went: new_start, left: new_end,
checked: new_checked)
end
end
end
验证事件以确保其时间并不奇怪:
def valid_time
if start_time == end_time
// Error...
end
if start_time > end_time
// Error...
end
end
application.rb 中的时区:
config.time_zone = 'Pacific Time (US & Canada)'
答案 0 :(得分:1)
您的not_ended?
方法已损坏。当事件在午夜之前开始,但在之后结束时,它不起作用。在这种情况下,日期是今天(假设数据基于开始时间),但事件结束后午夜的秒数小于当前时间。
在这些情况下,您不应该单独尝试处理日期和时间。您应该有办法检索事件结束的日期时间,并将其与当前日期时间进行比较。