ruby-on-rails - 有时我会因为时间的原因得到失败的香料。现在,不明白为什么
问题描述
所以我在模型中有一个方法
class << self
def last_week
start = Time.zone.now.beginning_of_week - 7.days
finish = start + 7.days
where('appointment_at >= ? AND appointment_at < ?', start, finish).order(appointment_at: :desc)
end
end
我为此方法编写规范。
RSpec.describe Appointment, type: :model, vcr: { record: :none } do
let!(:time) { Time.now }
let(:appointment_at) { time }
context '.last_week' do
let!(:scoped_appointment) { create(:appointment, appointment_at: time - 2.days) }
let!(:another_appointment) { create(:appointment, appointment_at: time - 16.days) }
it do
travel_to(time) do
expect(Appointment.last_week).to include(scoped_appointment)
expect(Appointment.last_week).not_to include(another_appointment)
end
end
end
end
有时我会因错误而失败。
expected #<ActiveRecord::Relation []> to include #<Appointment id: 18, lead_id: 27, body: nil, appointment_at: "2019-02-25 00:59:47", google_id: nil, ... "pending", user_id: 22, notify: nil, cc_emails: nil, appointment_minutes: nil, status_message: nil>
Diff:
@@ -1,2 +1,2 @@
-[#<Appointment id: 18, lead_id: 27, body: nil, appointment_at: "2019-02-25 00:59:47", google_id: nil, created_at: "2019-02-27 00:59:47", updated_at: "2019-02-27 00:59:47", timezone: nil, subject: "Meeting with Lead", address: nil, notification: nil, status: "pending", user_id: 22, notify: nil, cc_emails: nil, appointment_minutes: nil, status_message: nil>]
+[]
我不明白为什么?
我有一个建议,我应该紧紧地设置time
在spec_helper.rb
$now = DateTime.parse('2020-01-01 00:00:01 -0500')
会是对的吗?为什么?
解决方案
您的测试设置很脆弱。它会根据您运行规范的星期几而中断。
您的模型中的范围返回前一周的约会,从周一到周日(您正在调用beginning_of_week
并添加 7 天)
因此,如果您的测试在星期三运行,就像您提供的示例一样,约会的 appointment_at
字段将设置为星期一(因为您将其计算为Time.now - 2.days
)。这意味着您的范围将不包括该约会。
我建议您在设置中使用特定时间。鉴于您当前的设置,使用let(:time) { DateTime.parse('2019-02-25 00:00:00') }
应该可以
推荐阅读
- r - 用户定义函数的 R-For 循环实现
- javascript - 如何修复组件正在更改未定义类型的不受控制的输入
- google-apps-script - 如何使用脚本制作 Google 工作表模板,在每个实例创建时用户不需要授权脚本访问权限?
- java - 如何解决滚动视图中的图像视图滞后
- python - 相当于Scipy中matlab的“OutputFcn”?
- javascript - Unable to display error message in view using ejs templates
- android - 如何以编程方式阻止和允许其他应用程序在 android 中访问互联网?
- assembly - PDP 8 指令集长度比较
- vbscript - 调用自定义子例程时 VBscript 中的类型不匹配错误
- c# - 在 Unity 中,我应该何时使用协程而不是在 Update() 中减去 Time.deltaTime?