Rails 4:如何重置测试数据库? [英] Rails 4: How to reset test database?
问题描述
我在 Rails 4 上,注意到我的一些 RSpec 测试失败了,因为我的一些测试重构使用了一个 before 过滤器(大概是因为事务).这篇文章描述了一个类似的问题:
I'm on Rails 4 and have noticed some of my RSpec tests are failing because some of my test refactorings use a before filter (presumably because of transactions). This post describes a similar issue:
代替使用 DatabaseCleaner gem,是否有清除测试数据库的 rake 命令?我相信 rake db:test:prepare
在 Rails 4 中已被弃用.此外,如果在像
In lieu of using the DatabaseCleaner gem, is there a rake command to clear out the test database? I believe rake db:test:prepare
is deprecated in Rails 4. Also, if before transactions like
`post :create, user: Fabricate.attributes_for(:user)`
是否具有持久性,是否有替代的重构方式来避免手动清除测试数据库的需要?
are persistent, is there an alternative way of refactoring to avoid the need to manually clear out the test database?
推荐答案
一个矫枉过正的解决方案是:
An overkill solution would be:
bundle exec rake db:drop RAILS_ENV=test
bundle exec rake db:create RAILS_ENV=test
bundle exec rake db:schema:load RAILS_ENV=test
你可以在一个 rake 任务中完成这一切并运行它.
You could make this all in a rake task and run that.
来自 此处 是包含以下您的 spec_helper.rb
文件
Another solution from here is to include the following your spec_helper.rb
file
config.after :all do
ActiveRecord::Base.subclasses.each(&:delete_all)
end
免责声明:我尚未对此进行测试,您应该阅读 SO post 因为它可能不适用于所有情况.
Disclaimer: I have not tested this and you should read the SO post as it may not work in all situations.
话虽如此,我还是建议使用数据库清理器 gem 来避免这种情况.
That being said, I would recommend using the database cleaner gem to avoid situations such as this.
这篇关于Rails 4:如何重置测试数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!