简体   繁体   English

使用rspec-rails运行数据库

[英]run database with 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. 我正在尝试使用RSpec测试控制器,但出现问题,因为控制器中的功能需要数据库。

the line of code in the controller looks something like: 控制器中的代码行如下所示:

@myallresources = Myrsources.all

where Myresources just inherits from ActiveRecord::Base Myresources只是从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. 但是,由于没有数据库,因此没有要加载的内容,并且@myallresources只是一个空数组,从而导致测试失败。 Is there a way to connect to a database while running the rspec? 运行rspec时是否可以连接到数据库?

I am very new to RSpec and rails so any help would be very appreciated. 我对RSpec和rails非常陌生,因此对您的帮助非常感谢。 Thanks. 谢谢。

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 检查此页面上有关数据库隔离的部分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. 基本上,您必须模拟或存根ActiveRecord模型,因为应该在模型规格中单独测试它们。 Here's a simple example using mock_model: 这是一个使用模拟模型的简单示例:

before do
  mocks = (1..3).map { mock_model(MyResource) }
  MyResource.should_receive(:all).and_return(mocks)
end

Put this inside the same block where reside the describe definition testing for the actions that use MyResource.all . 将其放在使用MyResource.all的操作的describe定义测试所在的同一块中。

You can find good explanation of mocks and stubs in following links: 您可以在以下链接中找到有关模拟和存根的良好解释:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM