Search code examples
ruby-on-railstimerspecmomentjstimecop

RSpec Timecop failures around Date appear to be timezone related


We have some tests (specs) that are failing around Date/Time. Guessing it's a UTC issue but not sure why these specs passed last time project was touched (~8-months ago)!?!

#spec/features/comments/creation_spec.rb

feature 'Comment creation', type: :feature, js: true do
  include CommentsPageHelpers
  ...
  let!(:current_date) { Date.parse('2017-01-03') }
  ...

  background do
    Timecop.freeze(current_date)
    ...
  end

  after do
    Timecop.return
  end

  shared_examples 'added comment' do |position:, text:|
    scenario 'adds single comment' do
        ...
        expect(page).to have_text 'January 3rd, 2017'
      end
    end
  end

View (Angular template) #app/views/templates/comment.html.slim

.comment
  ...
  {{ comment.createdAt | moment: 'MMMM Do, YYYY' }}

#RSpec Failure

Comment creation for image behaves like added comment adds single comment
     Failure/Error: expect(page).to have_text 'January 3rd, 2017'
       expected to find text "January 3rd, 2017" in "John Snow First comment message January 2nd, 2017Remove"
     Shared Example Group: "added comment" called from ./spec/features/comments/creation_spec.rb:76
     # ./spec/features/comments/creation_spec.rb:42:in `block (4 levels) in <top (required)>'
     # ./spec/features/comments/creation_spec.rb:39:in `block (3 levels) in <top (required)>'

Solution

  • Changing the let! line to the two lines below seems to have fixed things. Don't know what else it might break or if it will break for devs in other timezones?!?

    Time.zone = 'Pacific Time (US & Canada)'
    let!(:current_date) { Time.parse('2017-01-03').in_time_zone }