所以我在模型中有一个方法
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') }
应该工作