【问题标题】:Using RSpec & Capybara to test Rails' created_at (TimeWithZone)使用 RSpec & Capybara 测试 Rails 的 created_at (TimeWithZone)
【发布时间】:2018-10-04 20:25:14
【问题描述】:

寻找在 Rails 应用程序中测试 TimeWithZone 对象呈现的最佳实践。

这失败了,至少我认为这是因为我们在创建对象时传递了一个日期,并且它作为2014-01-10T00:00:00.000Z存储在数据库中。

当渲染时

但是正在测试的是渲染页面在哪里

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
    ...
 ...

帮手:

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

它最终由 momentJS (javascript/Angular) 显示在页面上,它呈现日期:

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

由于我认为必须是本地化时区调整而失败:

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"

我们应该如何测试这个? FWIW Timecop 没有帮助。

【问题讨论】:

    标签: ruby-on-rails datetime rspec


    【解决方案1】:

    created_at 需要一个带时间的完整日期,而不仅仅是一个日期。我猜 Rails 会将您的字符串日期解析为 DateTime,并将 00:00:00 作为时间。尝试使用正确的时区创建正确的 DateTime 对象并将其作为值传递。这样一来,您就不会像 Rails 那样在幕后魔术留下任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多