我目前在运行 PostgreSQL 的 Rails 项目中使用 DatabaseCleaner
,并将其设置如下。
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation, { pre_count: true, reset_ids: true })
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
在我的一个 Rails 测试套件中,我打印了一个实例的 ID。我认为它应该是相对较小的数字,因为 clean_with(:truncate) 假设要清除数据库并对其运行 vacuum。但每次我运行测试时它都会增加。
测试通过并且使用什么顺序并不重要。但是为什么 clean_with(:truncation)
没有以它应该的方式工作?
====== 编辑 ======
这在 RSpec 测试的范围内。我知道序列号对性能没有影响,但每个 :suite 上的昂贵清洁(:截断)和使用便宜且快速的清洁(:交易)确实如此。所以我想了解为什么 clean_with(:truncation)
在运行测试套件之前没有为我重置 id 以获得干净的数据库状态。
最佳答案
这就是数据库的工作方式。
$ createdb test1
$ psql -d test1
> create table numbers (id serial, x integer);
> insert into numbers (x) values (1), (2), (3);
> select id from numbers order by id desc limit 1;
# 3
> truncate numbers;
> insert into numbers (x) values (1), (2);
> select id from numbers order by id desc limit 1;
# 5
如您所见,:truncate
对于数据库清理器意味着 truncate
。希望这是有道理的。
编辑——完全错过了这个问题。
:reset_ids
不起作用的原因是 postgresql 版本太低。使用 psql --version
找出您的版本,并从您需要 8.4 或更高版本的数据库清理器源中找到。
@restart_identity ||= db_version >= 80400 ? 'RESTART IDENTITY' : ''
我运行的是 9.3.5,运行良好。
> truncate numbers restart identity;
> insert into numbers (x) values (1);
> select * from numbers;
# id | x
# ----+---
# 1 | 1
为确保数据库清理器也能正常工作。
require 'rails/all'
require 'database_cleaner'
ActiveRecord::Base.establish_connection('postgres://localhost/test1')
class Number < ActiveRecord::Base; end
Number.count
# => 1
DatabaseCleaner.clean_with(:truncation, reset_ids: true)
它重置序列列。
$ psql -d test1
> insert into numbers (x) values (1);
> select * from numbers;
# id | x
# ----+---
# 1 | 1
关于ruby-on-rails - DatabaseCleaner.clean_with( :truncate) does not reset auto incremented id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31012405/