2011-03-10 61 views
28

我使用rails g model User生成了一個模型的裸導軌3應用程序。RSpec失敗:遷移後無法找到表...?

我(使用factory_girl_rails)增加了一個工廠:

Factory.define :user do |f| 
    f.email "[email protected]" 
    f.password "blah" 
    f.password_confirmation "blah" 
    f.display_name "neezer" 
end 

然後我添加了一個試驗:

require 'spec_helper' 

describe User do 

    subject { Factory :user } 

    it "can be created from a factory" do 
    subject.should_not be_nil 
    subject.should be_kind_of User 
    end 

end 

然後我使用rake db:migrate遷移我的數據庫

然後我跑使用rspec spec測試,測試失敗,出現以下:

Failures: 

    1) User can be created from a factory 
    Failure/Error: subject { Factory :user } 
    ActiveRecord::StatementInvalid: 
     Could not find table 'users' 
    # ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>' 
    # ./spec/models/user_spec.rb:8:in `block (2 levels) in <top (required)>' 

我很困惑,因爲我所做的僅僅是遷移我的數據庫,我schema.db文件反映的則是一個用戶表禮物,所以給了什麼?

我知道這是一個初學者的問題,但敲我的頭靠在牆上是不工作...

factory_girl (1.3.3) 
factory_girl_rails (1.0.1) 
rails (3.0.5) 
rspec-rails (2.5.0) 
sqlite3 (1.3.3) 

回答

82

嘗試執行

rake db:test:prepare 

這應該可以解決您的測試分貝。

+0

我需要運行,每當我做出新的遷移,或者只是它只是「引導」的測試數據庫? – neezer 2011-03-10 19:00:41

+1

只是一次,這就像db:migrate,我實際上總是把它放在一個自定義的任務中,我將它遷移,加載裝置,測試數據庫等等。 – Spyros 2011-03-10 19:49:59

+1

rake db如何處理的任何想法:test:prepare * does not * fix the problem? :( – Raphael 2012-01-27 19:10:16

2

這裏的要點是,rspec命令不會在您的測試數據庫上執行遷移。和rake db:migrate僅在當前環境中運行遷移,可能爲development。其他環境如productiontest最終沒有這些更改。

您可以運行

rake spec 

,將準備您的測試分貝(下降,並使用schema.rb)和運行所有測試。

由於the other answer建議,這樣的:

rake db:test:prepare 

還將設置您的測試分貝,但你必須運行後,該RSpec的命令,所以,我個人更喜歡第一個選項。

0

嘗試了這一點:

For rails version > 4.1+ this solution will work as the current scenario. 

but in Rails 4.1+, rake db:test:prepare is deprecated. 

嘗試使用

rake db:migrate RAILS_ENV=test (it will work for all version of rails) 
+0

我認爲當你爲你的內涵添加一些解釋時,它對OP和更多的訪問者會更有幫助。 – reporter 2014-08-04 09:46:59

+0

@reporter當然。 – 2014-08-04 09:49:45

+0

@reporter請檢查更新的答案。 – 2014-08-04 09:57:02