time_helper.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module TimeHelperCache
  3. %w[travel travel_to freeze_time travel_back].each do |method_name|
  4. define_method method_name do |*args, **kwargs, &blk|
  5. super(*args, **kwargs, &blk).tap do
  6. Rails.cache.clear
  7. Setting.class_variable_set :@@last_changed_at, 1.second.ago # rubocop:disable Style/ClassVars
  8. end
  9. end
  10. end
  11. # Similar to #travel_to, but fakes browser (frontend) time.
  12. # Useful when testing time that is generated in frontend
  13. def browser_travel_to(time)
  14. execute_script "window.clock = sinon.useFakeTimers({now: new Date(#{time.to_i * 1_000}), toFake: ['Date']})"
  15. end
  16. # Reimplementation of `setMonth(month[, date])` from the ECMAScript specification.
  17. # https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date.prototype.setmonth
  18. def frontend_relative_month(obj, month, date = nil)
  19. # 1. Let t be ? thisTimeValue(this value).
  20. t = obj
  21. # 2. Let m be ? ToNumber(month).
  22. m = month.to_i
  23. # 3. If date is present, let dt be ? ToNumber(date).
  24. if date.present?
  25. dt = date.to_i
  26. end
  27. # 4. If t is NaN, return NaN.
  28. raise InvalidDate if !t.is_a?(Time)
  29. # 5. Set t to LocalTime(t).
  30. t = t.in_time_zone
  31. # 6. If date is not present, let dt be DateFromTime(t).
  32. if date.nil?
  33. dt = t.day
  34. end
  35. # 7. Let newDate be MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)).
  36. new_year = t.year
  37. new_month = t.month + m
  38. if new_month > 12
  39. new_year += 1
  40. new_month -= 12
  41. end
  42. Time.zone.local(new_year, new_month, dt, t.hour, t.min, t.sec)
  43. # Ignore the rest, as `Time#local` already handles it correctly:
  44. # 8. Let u be TimeClip(UTC(newDate)).
  45. # 9. Set the [[DateValue]] internal slot of this Date object to u.
  46. # 10. Return u.
  47. end
  48. end
  49. RSpec.configure do |config|
  50. # make usage of time travel helpers possible
  51. config.include ActiveSupport::Testing::TimeHelpers
  52. config.include TimeHelperCache
  53. end