String与ActiveSupport :: TimeWithZone的比较失败

时间:2017-12-22 15:11:54

标签: ruby-on-rails datetime activerecord minitest fixtures

我的应用程序为用户提供了创建具有开始和结束时间的事件的机会:

>> Event.where('end_time < ?', 1.days.ago).first
  Event Load (0.3ms)  SELECT  "events".* FROM "events" WHERE (end_time < '2017-12-21 13:30:36.411209') ORDER BY "events"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Event id: 1, user_id: 1, place: "london", start_time: "2017-08-26 20:00", end_time: "2017-08-26 22:00", note: "Note", note_id: 355, picture: "dwarf_hammering.jpg", created_at: "2017-08-14 11:27:16", updated_at: "2017-08-14 11:27:16">

正如您所看到的,start_timeend_timeString的预定义格式,而Active Record可以将它们与时间实例进行比较。

我创建了一个Sidekiq作业来删除所有超过一天的事件:

class EventsCleanerWorker
  include Sidekiq::Worker

  def perform
    events = Event.where('end_time < ?', 1.days.ago)
    if events.any?
      events.delete_all
    end
  end
end

test/fixtures/events.yml内部我创建了6个事件:其中两个事件的日期超过一天end_time,如下所示:

event3:
  user: John
  place: "London"
  start_time: 3.days.ago.strftime("%Y-%m-%d %H:%M")
  end_time: 2.days.ago.strftime("%Y-%m-%d %H:%M")
  note: "A thrilling adventure"

然后我创建了以下测试:

def test_events_cleaner_worker_inline_mode
  assert Event.count == 6
  assert events(:event3).end_time < 1.days.ago
  EventsCleanerWorker.perform_async
  assert Event.all.reload.count == 4
  assert_equal 0, EventsCleanerWorker.jobs.size
end

但是,当我运行此测试时,我收到以下错误:

ArgumentError: comparison of String with ActiveSupport::TimeWithZone failed

此错误称为assert events(:event3).end_time < 1.days.ago
如果我删除此行,则测试失败,因为测试期望Event.all.reload.count为6而不是4.
我不知道为什么事件装置内的end_time生成的字符串无法与时间,虽然这在开发环境中是可能的。

1 个答案:

答案 0 :(得分:0)

灯具中的

start_timeend_time应嵌入ERB,如下所示:

event3:
  user: John
  place: "London"
  start_time: <%= 3.days.ago.strftime("%Y-%m-%d %H:%M") %>
  end_time: <%= 2.days.ago.strftime("%Y-%m-%d %H:%M") %>
  note: "A thrilling adventure"