我正在 Rails 中开发一个博客,当我试图测试我添加到 Post 模型的默认范围以使帖子按创建日期的降序排列时,我被卡住了。
邮政编码:
class Post < ActiveRecord::Base
attr_accessible :content, :name, :title
validates :title, presence: true,uniqueness: true
validates :name, presence: true
validates :content, presence: true
default_scope order: "posts.created_at DESC"
end
Rspec 代码:
describe "Posts descending order of creation date" do
let(:older_post) do
FactoryGirl.create(:post, created_at: 1.day.ago)
end
let(:newer_post) do
FactoryGirl.create(:post, created_at: 1.hour.ago)
end
it "should have the 2 posts in desc order" do
Post.all.should == [newer_post, older_post]
end
end
FactoryGirl 定义
FactoryGirl.define do
factory :post do
sequence(:title) { |n| "A book #{n}" }
name "Johnny"
content "Lorem Ipsum"
end
end
输出......F......
失败:
1) Post Posts descending order of creation date should have the 2 posts in desc order
Failure/Error: Post.all.should == [newer_post, older_post]
expected: [#<Post id: 1, name: "Johnny", title: "A book 1", content: "Lorem Ipsum", created_at: "2013-05-01 14:44:45", updated_at: "2013-05-01 15:44:45">, #<Post id: 2, name: "Johnny", title: "A book 2", content: "Lorem Ipsum", created_at: "2013-04-30 15:44:45", updated_at: "2013-05-01 15:44:45">]
got: [] (using ==)
Diff:
@@ -1,3 +1,2 @@
-[#<Post id: 1, name: "Johnny", title: "A book 1", content: "Lorem Ipsum", created_at: "2013-05-01 14:44:45", updated_at: "2013-05-01 15:44:45">,
- #<Post id: 2, name: "Johnny", title: "A book 2", content: "Lorem Ipsum", created_at: "2013-04-30 15:44:45", updated_at: "2013-05-01 15:44:45">]
+[]
# ./spec/models/post_spec.rb:54:in `block (3 levels) in <top (required)>'
在 1.03 秒内完成 9 个示例,1 个失败
失败的例子:
rspec ./spec/models/post_spec.rb:53 # Post Posts descending order of creation date should have the 2 posts in desc order
我还想提一下,当我在 Rails 控制台中键入 Post.all 时,我会按降序获取记录(所以我想要它们)。
有人可以给我一个关于问题可能是什么的建议吗?