Rails 测试数据库不会擦除
我正在运行 Rails 3.0.3 并将 rspec-rails 2.4.1 与 postgresql 数据库一起使用。每当我运行 RSpec 测试时,数据都会保留在最后。有谁知道如何让 Rails 或 rspec 在每次使用之间擦除测试环境的数据?
请告诉我是否有任何进一步的信息可以让我更轻松地回答我的问题。
谢谢!
特里斯坦
I'm running rails 3.0.3 and using rspec-rails 2.4.1 with a postgresql database. Whenever I run my RSpec tests, the data remains at the end. Does anyone know how to get rails or rspec to wipe the test environment's data between each use?
Please tell me if there's any further information that could make answering my question easier.
Thanks!
Tristan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
安装database_cleaner gem,然后将其添加到您的spec_helper.rb中。
Install the database_cleaner gem and then add this to your spec_helper.rb.
使用事务示例在每次测试运行后回滚数据
Use transactional examples to rollback the data after every test run
您不需要任何额外的 gem 来在运行之间清理测试数据库。在您的spec_helper.rb 文件中,按如下方式配置rspec:
You don't need any extra gem in order to clean your test DB between runs. In your spec_helper.rb file, configure rspec as follows:
我刚刚经历过的另一种可能性是使用了错误的
before
块。我不小心将
before
块设置为all
而不是each
:这导致
user
停留在整个 rspec 运行的数据库,这导致了验证冲突。相反,
before
应该是each
,以便通过rspec
运行,一切都保持干净:如果您犯了这个错误,那么您在一切恢复正常之前,可能需要手动清理测试数据库。最简单的方法可能是截断每个表(除了 schema_migrations 之外)。
Another possibility, that I just put myself through, is using the wrong
before
block.I accidentally set a
before
block as anall
instead of aneach
:This caused the
user
to stick around in the database for the entirerspec
run, which caused validation collisions.Instead, the
before
should be aneach
so that everything is kept clean through therspec
run:If you've made this mistake, then you will probably need to manually clean up your test database before things go back to normal. The simplest way to do that is probably to truncate each of the tables (aside from
schema_migrations
).