使用 rspec-rails 运行数据库
我正在尝试使用 RSpec 测试控制器,但遇到问题,因为控制器中的函数需要数据库。
控制器中的代码行看起来像这样:
@myallresources = Myrsources.all
其中 Myresources 只是继承自 ActiveRecord::Base
但是,因为没有数据库,所以没有任何可加载的内容,并且 @myallresources 只是一个空数组,导致测试失败。有没有办法在运行 rspec 时连接到数据库?
我对 RSpec 和 Rails 非常陌生,因此我们将不胜感激。谢谢。
I am trying to test a controller with RSpec but am having a problem because a function in the controller requires a database.
the line of code in the controller looks something like:
@myallresources = Myrsources.all
where Myresources just inherits from ActiveRecord::Base
however, because there is no database, there is nothing to load and @myallresources is just an empty array, causing the test to fail. Is there a way to connect to a database while running the rspec?
I am very new to RSpec and rails so any help would be very appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应在控制器规范中使用数据库连接。
检查此页面上有关数据库隔离的部分 http://rspec.info/rails/writing/controllers。基本上
,您必须模拟或存根您的 ActiveRecord 模型,因为这些模型应该在模型规范中单独测试。下面是一个使用 mock_model 的简单示例:
将其放在驻留
describe
定义测试的同一块中,以测试使用MyResource.all
的操作。您可以在以下链接中找到模拟和存根的详细解释:
You shouldn't use a database connection in your controller specs.
Check the section about database isolation on this page http://rspec.info/rails/writing/controllers.html
Basically you have to mock or stub your ActiveRecord models, as those should be tested separately in the models specs. Here's a simple example using mock_model:
Put this inside the same block where reside the
describe
definition testing for the actions that useMyResource.all
.You can find good explanation of mocks and stubs in following links: