2

我正在使用 FactoryGirl 为 Rails 相关的 gem 创建日期维度模型的实例。我的工厂是这样的:

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

我已经阅读了一堆与序列相关的其他问题,但似乎我并没有犯其中发现的错误。这是一个不同的(可能更愚蠢的)错误。它是什么?

4

1 回答 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
于 2012-06-21T17:04:35.530 回答