2016-04-19 24 views
1

私はRSpecを理解しようとしており、いくつかの問題があります。 私は私の基本的なテストを実行する場合: 障害:Rails RSpec random db

1) Post orders by creation date 
    Failure/Error: Post.order('created_at desc').all.to_a.should == ([@new_post, @post]) 

     expected: [#<Post id: 980190990, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">] 
      got: [#<Post id: 980190990, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, #<Post id: 980190962, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">, #<Post id: 298486374, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">] (using ==) 
     Diff: 
     @@ -1,3 +1,5 @@ 
     [#<Post id: 980190990, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, 
     - #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">] 
     + #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, 
     + #<Post id: 980190962, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">, 
     + #<Post id: 298486374, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">] 

あなたがこの問題の原因が何であるかを知っています

require 'rails_helper' 

describe Post do 

    before do 
    @post = Post.create!(title: 'foobar1', content: 'foobar'*5) 
    end 

    it 'orders by creation date' do 
    @new_post = Post.create!(title: 'foobar1', content: 'foobar'*5) 
    Post.order('created_at desc').all.to_a.should == ([@new_post, @post]) 
    end 
end 

をそれは私がデシベルでいくつかのより多くの神秘的な記事を持っているように見えますか?

答えて

1

RSpecは、通常、Database Cleanerと手を携えて行きます。

この宝石は、データベースがテスト間で適切にリセットされるようにします。以下に標準設定スクリプトがあります。

# spec/rails_helper.rb 
require 'database_cleaner' 

RSpec.configure do |config| 
    config.use_transactional_fixtures = false 

    config.before(:suite) do 
    DatabaseCleaner.clean_with(:truncation) 
    end 

    config.before(:each) do |example| 
    DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction 
    DatabaseCleaner.start 
    end 

    config.after(:each) do 
    DatabaseCleaner.clean 
    end 
end 
+0

ありがとう、それはトリックでした。 –