2011-03-10 64 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