使用FactoryGirl使用Rspec进行测试时,Rails模型中的Default_scope

时间:2013-05-01 15:51:44

标签: ruby-on-rails rspec factory-bot

我正在开发一个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时,我按降序获取记录(因此我想要它们)。

有人可以就问题可能给我一个建议吗?

1 个答案:

答案 0 :(得分:1)

请注意,let在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

注意,使用let!代替let 或者,使用before作为:

  describe "Posts descending order of creation date" do

    it "should have the 2 posts in desc order" do
    @older_post = FactoryGirl.create(:post, created_at: 1.day.ago)
    @newer_post = FactoryGirl.create(:post, created_at: 1.hour.ago)

    Post.all.should == [@newer_post, @older_post]
    end    
  end

如果有效,请告诉我。 :)