[英]Does rspec access the database when tests are run?
I'm using rspec-rails to test a controller in my rails application. 我正在使用rspec-rails在Rails应用程序中测试控制器。 In one instance, I'm creating new objects to test that they're properly assigned to instance variables.
在一个实例中,我正在创建新对象以测试它们是否已正确分配给实例变量。
describe MainController do
describe "GET #index" do
it "properly assigns a colored ball" do
ball1 = Ball.create(color: 'red')
get :index
expect(assigns(:red_balls)).to eq([ball1])
end
end
end
When I run the test, does rspec access the database to create ball1 and then delete it once the test is run? 运行测试时,rspec是否访问数据库以创建ball1,然后在测试运行后将其删除?
From the snippet in your question, Yes Rspec
access the DB configured as test in the database.yml
file, if you want to clean out the DB/Records created by Rspec
you can use the database_cleaner gem you can configure it as you deem fit. 从您的问题的
Rspec
可以, Rspec
可以访问在database.yml
文件中配置为测试的database.yml
,如果要清除由Rspec
创建的数据库/记录,则可以使用database_cleaner gem来配置您认为合适的数据库 。
eg: 例如:
add gem database_cleaner
to your Gemfile
将
gem database_cleaner
添加到您的Gemfile
and the below to your spec_helper.rb
file as specified by the database_cleaner
documentation: 并将以下内容输入到
database_cleaner
文档指定的spec_helper.rb
文件中:
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
Then database_cleaner
would truncate the tables in the test db
and leave them in a pristine state 然后,
database_cleaner
将截断test db
的表,并使它们保持原始状态
To add to what bjhaid said above - Rspec should only be accessing you 'test' database. 要补充上面bjhaid所说的-Rspec应该只在访问您的“测试”数据库。 Check out the config/database.yml to see the configuration of your different databases.
检出config / database.yml以查看不同数据库的配置。
So you do not have to worry about things in your development or production databases interfering with your testing database. 因此,您不必担心开发或生产数据库中的事情会干扰测试数据库。
Yes, RSpec allows your database calls to go through, but with the rspec-rails gem under the default configuration, it will execute each test within a database transaction and will roll back that transaction at the end of each example with no action required on your part. 是的,RSpec允许您的数据库调用通过,但是在默认配置下使用rspec-rails gem时,它将在数据库事务中执行每个测试,并在每个示例结束时回滚该事务,而无需执行任何操作部分。 No additional gem is required.
不需要其他宝石。 See https://relishapp.com/rspec/rspec-rails/docs/transactions .
请参阅https://relishapp.com/rspec/rspec-rails/docs/transactions 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.