Ruby/Rails獲得了一些單元測試正則表達式問題。Ruby on 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-zA-Z] {3} \ d {1,2} \ z/to匹配「10月8日」。
考慮到正則表達式對我來說很合適,並且我已經在http://rubular.com/上測試了表達式,這真是非常棒。這裏所有其他的測試都通過了。我也嘗試在\d
之後刪除字符串分隔符和量詞的開始/結尾。
有關爲什麼會發生這種情況的任何想法?
我在3.2和4.0中測試了你的代碼,它工作正常。你的正則表達式很好。別的東西壞了...... –