如何解决使用 rspec 在 Ruby 上测试 Rails -- 由于加载 rspec 时的 TRUNCATE 表而花费的时间太长
我是 Ruby 和 Rails 的新手。我刚刚开始与两者合作。
我正在开发的应用程序使用 rspec
在 Ruby on Rails 中运行测试,并且在每一轮中所有数据库表都被截断。拖尾 log/test.log
显示许多带有 TruncATE TABLE <table>
的行。我看到很多帖子使用 Database cleaner
gem 和如下配置:
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
这将跳过 TruncATE 表。或更全面的配置,例如:
config.before(:suite) do
DatabaseCleaner.clean_with :transaction
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:all) do
DatabaseCleaner.start
end
config.after(:all) do
DatabaseCleaner.clean
end
但它不起作用。
还有其他帖子建议在 Postgres 配置中设置 fsync=off
,其他教程也建议设置 full_page_writes=off
。但我没有找到关于 MysqL 的任何信息,我正在使用的 DBMS。
MysqL 有类似的配置吗?
解决方法
以下是我的 spec/rails_helper.rb
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord,or you'd prefer not to run each of your
# examples within a transaction,remove the following line or assign false
# instead of true.
# References:
# https://relishapp.com/rspec/rspec-rails/docs/transactions
# http://stackoverflow.com/questions/21493970/databasecleaner-rspec-what-is-the-correct-configuration
# http://devblog.avdi.org/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/
config.use_transactional_fixtures = false
# https://github.com/DatabaseCleaner/database_cleaner#rspec-example
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:suite) do
begin
DatabaseCleaner.start
ensure
DatabaseCleaner.clean
end
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location,for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below,and instead
# explicitly tag your specs with their type,e.g.:
#
# RSpec.describe UsersController,:type => :controller do
# # ...
# end
#
# The different available types are documented in the features,such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
我在我多年的项目中使用了很长时间。也许你可以试试这个。
您还可以查看我在探索正确使用 database_cleaner 时记录的参考资料。顺便说一句,在我的应用程序中,我使用的是 database_cleaner
,版本为 1.5.3
。
希望有所帮助。谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。