3

Got a bit of unit testing regex issue with Ruby/Rails.

Running:

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

Writing an applicaton_helper method that will format a date depending on how far back the date is. Here's the method:

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

This seems to be giving the desired results, but for some reason, the following test is failing:

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

The last test fails, giving

1) Failure: 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]: Expected /\A[a-zA-Z]{3} \d{1,2}\z/ to match "Oct 8".

Which is really bizzare, given that the regex looks ok to me and I've tested the expression on http://rubular.com/. All other tests here are passing. I've also tried removing the beginning/end of string delimiters and the quantifiers after \d.

Any thoughts as to why this is occurring?

  • I tested your code in both 3.2 and 4.0, and it works fine. Your regex is fine. Something else is broken.... – Yosep Kim Oct 15 '13 at 20:31

1 Answers1

3

your humanize_datetime adds an extra space if date of month is < 10, because of "%b %e". Resulting string is not "Oct 8" but "Oct  8".

You should use "%b %-d" or change your regular expression.

Edit: minus prefix might not work on all systems, see this answer for more details.

Community
  • 1
  • 1
mechanicalfish
  • 12,696
  • 3
  • 46
  • 41