Rspec returns 错误 Ruby 日期月份。 Ruby 的 Class returns 正确的那个
Rspec returns wrong Ruby Date month. Ruby's Class returns the right one
这很奇怪?我缺少什么魔法?
class Calendar
def initialize
@date = Time.new
end
def month
@date.strftime("%B")
end
def calendar
calendar = { 'month' => self.month }
end
end
c = Calendar.new
puts c.calendar => {"month"=>"February"}
calendar_spec.rb
require 'date'
require 'spec_helper'
require 'calendar'
describe Calendar do
subject { Calendar.new }
context "calendar" do
it "should save current month into calendar hash" do
expect(subject.calendar['month']).to eq(Date.new.strftime("%B"))
end
end
$> rspec spec
Failures:
1) Calendar calendar should save current month into calendar hash
Failure/Error: expect(subject.calendar['month']).to eq(Date.new.strftime("%B"))
expected: "January"
got: "February"
(compared using ==)
# ./spec/calendar_spec.rb:25:in `block (3 levels) in <top (required)>'
Date#new
doesn't return today's date。您在 class 中使用 Time.new
,在测试中使用 Date.new
。在这两种情况下,您可能应该使用 Time.now
。
不带参数的 Date.new
不是 return 今天的日期,而是:
Date.new
# => Mon, 01 Jan -4712
相反,您可以使用 Date.today
:
expect(subject.calendar['month']).to eq(Date.today.strftime("%B"))
除了 Date.new
问题(它默认为 Julian 时期的开始,即公元前 4712 年),您的测试和代码都使用当前日期。当 运行 在不同日期进行测试时,这可能会导致意外行为。
通常最好明确设置当前时间,例如:
class Calendar
def initialize(time = Time.new)
@date = time
end
# ...
end
在你的测试中:
describe Calendar do
let(:now) { Time.new(2014, 1, 1) }
subject { Calendar.new(now) }
describe "#month" do
it "returns the current month's name" do
expect(subject.month).to eq('January')
end
end
#...
end
这很奇怪?我缺少什么魔法?
class Calendar
def initialize
@date = Time.new
end
def month
@date.strftime("%B")
end
def calendar
calendar = { 'month' => self.month }
end
end
c = Calendar.new
puts c.calendar => {"month"=>"February"}
calendar_spec.rb
require 'date'
require 'spec_helper'
require 'calendar'
describe Calendar do
subject { Calendar.new }
context "calendar" do
it "should save current month into calendar hash" do
expect(subject.calendar['month']).to eq(Date.new.strftime("%B"))
end
end
$> rspec spec
Failures:
1) Calendar calendar should save current month into calendar hash
Failure/Error: expect(subject.calendar['month']).to eq(Date.new.strftime("%B"))
expected: "January"
got: "February"
(compared using ==)
# ./spec/calendar_spec.rb:25:in `block (3 levels) in <top (required)>'
Date#new
doesn't return today's date。您在 class 中使用 Time.new
,在测试中使用 Date.new
。在这两种情况下,您可能应该使用 Time.now
。
Date.new
不是 return 今天的日期,而是:
Date.new
# => Mon, 01 Jan -4712
相反,您可以使用 Date.today
:
expect(subject.calendar['month']).to eq(Date.today.strftime("%B"))
除了 Date.new
问题(它默认为 Julian 时期的开始,即公元前 4712 年),您的测试和代码都使用当前日期。当 运行 在不同日期进行测试时,这可能会导致意外行为。
通常最好明确设置当前时间,例如:
class Calendar
def initialize(time = Time.new)
@date = time
end
# ...
end
在你的测试中:
describe Calendar do
let(:now) { Time.new(2014, 1, 1) }
subject { Calendar.new(now) }
describe "#month" do
it "returns the current month's name" do
expect(subject.month).to eq('January')
end
end
#...
end