Last Updated: September 09, 2019
·
12.1K
· ryrych

Freezing time with time zone in RSpec

Suppose that you’re testing logic that depends on Time:

let(:frozen_time) { Time.zone.parse('2016-08-06 14:15:00 +0200') }

let(:frozen_time) { Time.zone.parse('2016-08-06 14:15:00') }

All specs pass, but Travis reports that one specs fails. Instead of expected: 2016-08-06T14:15:00Z it outputs 2016-08-06T12:15:00Z. The simple solution is to be one the same page; freezing time with some timezone (I chose ‘Warsaw / Poland’).

describe '.stages' do
  let(:frozen_time) { Time.zone.parse('2016-08-06 14:15:00 +0200') }
  subject { described_class.stages }

  before { Timecop.travel(frozen_time) }
  after { Timecop.return }

  context 'overdue' do
    it { expect(stage_in_iso(:overdue)).to eq('2016-08-06T12:15:00Z') }
  end
end