【问题标题】:Ruby on Rails Unit Test Fails On Date TestRuby on Rails 单元测试在日期测试中失败
【发布时间】:2013-10-23 18:58:18
【问题描述】:

在 Ruby/Rails 中遇到了一些单元测试正则表达式问题。

跑步:

  • Rails 4.0.0
  • Ruby 2.0.0-p247
  • RVM 1.23.5
  • Mac OSX 10.8.5

编写一个applicaton_helper 方法,该方法将根据日期的回溯来格式化日期。方法如下:

module ApplicationHelper
  def humanize_datetime time
    time = Time.at(time)
    date = time.to_date

    today   = Date.today

    time_format = "%-I:%M %p"

    #if the time is within today, we simply use the time
    if date == today
      time.strftime time_format

    # if  the time is within the week, we show day of the week and the time
    elsif today - date < 7
      time.strftime "%a #{time_format}"

    # if time falls before this week, we should the date (e.g. Oct 30)
    else
      time.strftime "%b %e"
    end
  end
end

这似乎给出了预期的结果,但由于某种原因,以下测试失败了:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase

  test "humanize_dateime should display only time when datetime is within today" do
    formatted = humanize_datetime Time.now
    assert_match /\A\d{1,2}\:\d\d (AM|PM)\z/, formatted
  end

  test "humanize_datetime should display day of week and time when datetime is not today but within week" do
    yesterday_formatted = humanize_datetime (Date.today - 1).to_time # yesterday
    assert_match /\A[a-zA-z]{3} \d{1,2}\:\d\d (AM|PM)\z/, yesterday_formatted

    within_week_formatted = humanize_datetime (Date.today - 6).to_time # just within this week
    assert_match /\A[a-zA-z]{3} \d{1,2}\:\d\d (AM|PM)\z/, within_week_formatted
   end

   test "humanize_datetime should display date when datetime is before this week" do
     last_week_formatted = humanize_datetime (Date.today - 7).to_time
     assert_match /\A[a-zA-Z]{3} \d{1,2}\z/, last_week_formatted
   end
end

最后一次测试失败,给

1) 失败: ApplicationHelperTest#test_humanize_datetime_should_display_date_when_datetime_is_before_this_week [/Users/mohammad/rails_projects/stopSmoking/test/helpers/application_helper_test.rb:20]: 预期 /\A[a-zA-Z]{3} \d{1,2}\z/ 匹配“10 月 8 日”。

这真的很奇怪,因为正则表达式对我来说看起来不错,而且我已经在 http://rubular.com/ 上测试了表达式。这里的所有其他测试都通过了。我还尝试删除字符串分隔符的开头/结尾以及\d 之后的量词。

关于为什么会发生这种情况的任何想法?

【问题讨论】:

  • 我在 3.2 和 4.0 中都测试了您的代码,并且运行良好。你的正则表达式很好。别的东西坏了....

标签: ruby-on-rails ruby regex unit-testing


【解决方案1】:

如果月份的日期 humanize_datetime 会添加一个额外的空格,因为 "%b %e"。结果字符串不是"Oct 8",而是"Oct  8"

您应该使用"%b %-d" 或更改您的正则表达式。

编辑:减号前缀可能不适用于所有系统,有关详细信息,请参阅this 答案。

【讨论】:

  • 太棒了。解决了。这就是 Ruby 文档所说的“空白填充”的意思。太棒了,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多