如何在单元测试中重新加载模型类
如何在单元测试中重新加载 ActiveRecord 模型类? (在 Ruby on Rails 版本 1.2.6 中)
我有一个单独运行时运行正常的单元测试,例如 rake test:recent RAILS_ENV=test
。
当与所有其他单元测试(例如 rake test:units RAILS_ENV=test
)一起运行时,单元测试将会失败。
失败的单元测试与其他模型有很多 ActiveRecord 关系...在运行失败的单元测试之前需要重新加载模型。我该怎么做?
更新
我找到了一种方法来解决断言失败,而无需重新加载我的数据模型。现在,测试可以单独或一起运行。
How do I reload an ActiveRecord model class in a unit test? (In Ruby on Rails version 1.2.6)
I have a unit test that runs OK when run in isolation, such as rake test:recent RAILS_ENV=test
.
The unit test will fail when run with all other unit tests, such as rake test:units RAILS_ENV=test
.
The unit test that fails has a lot of ActiveRecord relationships with other models... models that need to get reloaded before I run the failing unit test. How do I do this?
Update
I found a way to work around the assertation failures without having to reload my data model. Tests now run OK in isolation or together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您的测试中不应该有这样的依赖关系,所以这可能是一个错误。有时您可能需要在测试中重新加载模型,但每个测试应该完全独立,并且应该使系统处于可接受的一致状态。
默认情况下用于单元测试的事务系统应该恢复您对记录所做的任何更改,因此您不应该在不同的测试方法之间共享数据。
您认为您正在做的某些具体事情可能有问题吗?
You shouldn't have dependencies in your tests like this in the first place, so this is probably a mistake. There are occasions you may need to reload models within your tests, but each test should be entirely independent and should leave the system in an acceptably consistent state.
The transaction system used by default for unit tests is supposed to revert any changes you have made to records, and because of this you should not be sharing data between different test methods.
Is there something specific you're doing you think might be problematic?