2016-04-19 46 views
1

我想弄清楚RSpec並有一些問題。 當我跑我的基本測試:Rails的RSpec隨機db

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 

它看起來像我在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">] 

你知道這是什麼問題的原因是什麼?

回答

1

RSpec通常與Database Cleaner齊頭並進。

該gem確保您的數據庫在測試之間正確重置。下面你可以找到一個標準的配置腳本。

# 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

謝謝,它做到了。 –