测试/test_helper.rb :
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'database_cleaner'
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation, pre_count: true, reset_ids: true)
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
def setup
DatabaseCleaner.start
end
def teardown
DatabaseCleaner.clean
p '-------- DB Cleaned ---------'
end
end
我的测试单元文件:(test1 和 2 是重复的)
require 'test_helper'
class ItemTest < ActiveSupport::TestCase
test "test1" do
i = Item.create!
p ActiveRecord::Base.connection.execute("SELECT auto_increment FROM information_schema.tables WHERE table_schema = 'tmi_game_test' AND table_name = 'items';").first
assert_equal 1, Item.count
assert_equal 1, i.id
end
test "test2" do
i = Item.create!
p ActiveRecord::Base.connection.execute("SELECT auto_increment FROM information_schema.tables WHERE table_schema = 'tmi_game_test' AND table_name = 'items';").first
assert_equal 1, Item.count
assert_equal 1, i.id
end
end
结果:
# Running:
[2]
"-------- DB Cleaned ---------"
.[3]
"-------- DB Cleaned ---------"
F
Finished in 0.142886s, 13.9972 runs/s, 27.9944 assertions/s.
1) Failure:
ItemTest#test_test2 [test/models/item_test.rb:45]:
Expected: 1
Actual: 2
2 runs, 4 assertions, 1 failures, 0 errors, 0 skips
为什么不起作用?我的错误在哪里?
最佳答案
这是预期的行为。您正在使用 :transaction
策略来清理表。这意味着每个测试都包含在一个事务中,该事务在测试后(在 teardown
期间)被 ROLLBACK
编辑。
您没有说明您使用的是哪个数据库,但是 ROLLBACK
不会重置 AUTO_INCREMENT
值,在 MySQL 中也是如此(参见 bug #6714 )也不在 PostgreSQL 中(参见 bug #1139 )。
按照这个SO answer我认为您不应该在测试中依赖 auto_increment ID 值。我认为您应该测试其他属性,而不是断言您正在使用预期的记录。
如果您确实需要重置您的AUTO_INCREMENT
计数器,请改用:truncation
清理策略。 IE。删除 clean_with
行并将策略设置为 :truncation
。虽然它比事务慢得多。
关于ruby-on-rails - DatabaseCleaner 不要重置 Rails 测试单元中的自动增量索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36222996/