有时我会因为Time.s而使香料失败。现在,我不明白为什么

时间:2019-02-27 01:11:29

标签: ruby-on-rails rspec rspec-rails rspec3

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

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

会正确吗?以及为什么?

1 个答案:

答案 0 :(得分:1)

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

模型中的范围返回前一周(周一至周日)的约会(您正在呼叫beginning_of_week并为其添加7天)

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

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