有时因为Time.now我得到失败的香料,无法理解为什么

问题描述 投票:1回答:1

所以我在模型中有一个方法

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')

会是对的吗?为什么?

ruby-on-rails rspec rspec-rails rspec3
1个回答
1
投票

您的测试设置很脆弱。它将根据您运行规范的星期几而中断。

模型中的范围返回前一周,周一到周日的约会(您正在调用beginning_of_week并为其添加7天)

因此,如果您的测试在星期三运行,就像您提供的示例一样,约会的appointment_at字段将设置为星期一(因为您将其计算为Time.now - 2.days)。这意味着您的范围不会涵盖该预约。

我建议您在设置中使用特定时间。鉴于您当前的设置,使用let(:time) { DateTime.parse('2019-02-25 00:00:00') }应该工作

© www.soinside.com 2019 - 2024. All rights reserved.