Meltemi
Meltemi

Reputation: 38359

Using RSpec & Capybara to test Rails' created_at (TimeWithZone)

Looking for best practice in testing the rendering of a TimeWithZone object in a Rails app.

This fails because, at least I think it's because we pass a date when we create the object and it's stored in the DB as 2014-01-10T00:00:00.000Z.

Yet when rendered

But what is being tested is the rendered page where

let(:attachment) { create :attachment, created_at: '2014-01-10' }

    background do
      user.article.attachments << [attachment]
      stub_image_convert(new_file[:url])
      stub_request(:put, new_file[:s3_request])

      visit article_path(user.article, as: user)
    end

    scenario 'uploaded files are added to the list' do
      expect(page).to have_css '.attachment-item', count: 1
      within file_group_selector(position: 1) do
        upload_date_present 'January 10, 2014'
        file_previews_present count: 1
      end
    ...
 ...

helper:

  def upload_date_present(date)
    expect(page).to have_css 'grouped-attachments .group-title', text: date
  end

and it's ultimately displayed on page by momentJS (javascript/Angular) which renders the date:

  newAttachment.groupDate = moment().format('LL')

and fails because of what I assume must be a localized timezone adjustment:

Failure/Error: expect(page).to have_text 'January 10th, 2014'
   expected to find text "January 10th, 2014" in "John Snow First comment message January 9th, 2014"

How should we be testing this? FWIW Timecop doesn't help.

Upvotes: 1

Views: 486

Answers (1)

arieljuod
arieljuod

Reputation: 15838

created_at expects a full date with time, not just a date. I guess Rails parses your string date as a DateTime with 00:00:00 as time. Try creating a proper DateTime object with the correct timezone and pass that as the value. That way you leave nothing to the under the hood magic that Rails does.

Upvotes: 1

Related Questions