【发布时间】:2011-11-21 14:47:14
【问题描述】:
在我的项目中,user 将有许多 items,它们的 onshelf_at 属性在创建时默认为 DateTime.now。
# item.rb
class Item < ActiveRecord::Base
before_create :calculate_onshelf_time
default_scope :order => 'items.onshelf_at DESC'
def calculate_onshelf_time
self.onshelf_at = DateTime.now
end
end
在用户模型测试中,我试图说服自己检索到的订单确实是items.onshelf_at DESC。于是我做了下面的sn-p,结果却是反了。 (即[@item1, @item2])
# spec/models/user_spec.rb
before :each do
@user = User.create(@attr)
@item1 = Factory(:item, :owner=>@user, :onshelf_at => 2.days.ago, :created_at => 2.days.ago)
@item2 = Factory(:item, :owner=>@user, :onshelf_at => 1.day.ago, :created_at => 1.day.ago)
end
it "should have the right items in the right order" do
@user.items.should == [@item2, @item1]
end
我检查了控制台,发现 onshelf_at 没有监听 Factory Girl 的实例初始化。取而代之的是,它遵循 before_create 规则,并重视运行测试的时间!
Failure/Error: @user.items.should == [@item2, @item1]
expected: [#<Item id: 2, description: "this is an item", img_link: "http://www.example.com/photos/some_pic.jpg", category_id: 5, onshelf: true, created_at: "2011-11-20 11:19:15", updated_at: "2011-11-21 11:19:15", onshelf_at: "2011-11-21 11:19:15", owner_id: 1>, #<Item id: 1, description: "this is an item", img_link: "http://www.example.com/photos/some_pic.jpg", category_id: 5, onshelf: true, created_at: "2011-11-19 11:19:15", updated_at: "2011-11-21 11:19:15", onshelf_at: "2011-11-21 11:19:15", owner_id: 1>]
got: [#<Item id: 1, description: "this is an item", img_link: "http://www.example.com/photos/some_pic.jpg", category_id: 5, onshelf: true, created_at: "2011-11-19 11:19:15", updated_at: "2011-11-21 11:19:15", onshelf_at: "2011-11-21 11:19:15", owner_id: 1>, #<Item id: 2, description: "this is an item", img_link: "http://www.example.com/photos/some_pic.jpg", category_id: 5, onshelf: true, created_at: "2011-11-20 11:19:15", updated_at: "2011-11-21 11:19:15", onshelf_at: "2011-11-21 11:19:15", owner_id: 1>] (using ==)
我该如何解决这个问题?
【问题讨论】:
标签: ruby-on-rails model rspec factory factory-bot