2015-02-11 40 views
0

這很奇怪嗎?我錯過了什麼魔法?Rspec返回錯誤的Ruby Date月份。 Ruby的類返回正確的

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)>' 

回答

1

Date.new沒有參數沒有返回今天的日期,但:

Date.new 
# => Mon, 01 Jan -4712 

相反,你可以使用Date.today

expect(subject.calendar['month']).to eq(Date.today.strftime("%B")) 
1

Date#newdoesn't return today's date。你在你的班級中使用Time.new,在你的測試中使用Date.new。在這兩種情況下,您應該都可以使用Time.now

1

除了Date.new問題(默認爲朱利安週期的開始,即公元前4712年),您的測試和您的代碼都使用當前日期。在不同日期運行測試時,這可能會導致意外的行爲。

它通常是更好地明確設置當前時間,e.g:

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