2012-06-21 42 views
2

我使用FactoryGirl爲Rails相關的gem創建日期維度模型的實例。我廠是這樣的:FactoryGirl序列不遞增

FactoryGirl.define do 
    sequence :next_day do |n| 
    Date.new(2000,12,31) + n.days 
    end 

    factory :date_dimension do 
    the_date = FactoryGirl.generate(:next_day) 
    date {the_date.to_s} 
    calendar_year {the_date.strftime("%Y")} 
    (...other attributes created similarly to calendar_year) 
    end 

end 

出於無奈我實際上建立了一個小測試,以證明有什麼不工作:

describe "working date factories" do 
    before(:all) do 
    @date_dimension = FactoryGirl.create(:date_dimension) 
    @jan_two = FactoryGirl.create(:date_dimension) 
    end 

    describe "sequence incrementing" do 
    it "returns a date dimension object ok" do 
     @date_dimension.date.should == "2001-01-01" 
    end 
    it "returns the next date in the sequence" do 
     @jan_two.date.should == "2001-01-02" 
    end 
    end 
end 

當我運行測試,我得到:

working date factories 
    sequence incrementing 
    returns a date dimension object ok 
    returns the next date in the sequence (FAILED - 1) 

Failures: 

    1) working date factories sequence incrementing returns the next date in the sequence 
    Failure/Error: @jan_two.date.should == "2001-01-02" 
     expected: "2001-01-02" 
      got: "2001-01-01" (using ==) 

我讀過一系列與序列有關的其他問題,但似乎並沒有發現其中的錯誤。這是一個不同的(可能是數字)錯誤。它是什麼?

+0

我真的無法重現你的問題。我試着定義一個幾乎完全相同的工廠,並且它的順序很好。然後我懷疑它可能與使用塊和date_dimension工廠內的局部變量有關,但無濟於事。對我來說,它工作得很好.. – Tigraine

+0

嗯,計數器是從0開始的嗎? – apneadiving

+0

我的理論是,如果第一個例子通過,那表明計數器從1開始,因爲12/31/2000 + 1.day應該是1/1/2001。它通過,所以我認爲這表明計數器從1開始。 –

回答

1

我終於找到了一種可行的方法,無論如何可能會好一點。我仍然不明白爲什麼上面的代碼不起作用 - 如果有人能夠向我解釋(也許參考文檔或源代碼的一部分),我會繼續接受這個答案 - 這篇文章只是爲了那些追隨者。這裏是什麼工作:

FactoryGirl.define do 

    factory :date_dimension do 
    sequence(:date) { |n| (Date.new(2000,12,31) + n.days).to_s } 
    calendar_year { Date.parse(date).strftime("%Y") } 
    day_of_week { Date.parse(date).strftime("%A") } 
    end 

end 

上面的代碼通過測試:

describe "working date factories" do 
    before(:all) do 
    @date_dimension = FactoryGirl.create(:date_dimension) 
    @jan_two = FactoryGirl.create(:date_dimension) 
    end 

    describe "sequences" do 
    it "returns the proper first date in the sequence" do 
     @date_dimension.date.should == "2001-01-01" 
     @date_dimension.calendar_year.should == "2001" 
     @date_dimension.day_of_week.should == "Monday" 
    end 
    it "returns the next date in the sequence" do 
     @jan_two.date.should == "2001-01-02" 
     @jan_two.calendar_year.should == "2001" 
     @jan_two.day_of_week.should == "Tuesday" 
    end 
    end 
end