Ruby on rails DatabaseCleaner不重置rails测试单元中的自动增量索引

Ruby on rails DatabaseCleaner不重置rails测试单元中的自动增量索引,ruby-on-rails,unit-testing,database-cleaner,Ruby On Rails,Unit Testing,Database Cleaner,test/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_

test/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和test2是重复的

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

为什么不起作用?我的错误在哪里?

这是预期的行为。您正在使用:事务策略来清理表。这意味着每个测试都包装在一个事务中,该事务在测试结束后在拆卸过程中回滚

您没有说明使用哪个数据库,但回滚不会重置自动增量值,无论是在MySQL see还是在PostgreSQL see中

根据这一点,我认为您在测试中不应该依赖于自动增量ID值。我认为您应该测试其他属性,而不是断言您正在使用预期的记录


如果确实需要重置自动递增计数器,请使用:截断清理策略。也就是说,删除带有行的clean_,并将策略设置为:截断。但它比事务处理慢得多。

DatabaseCleaner.clean_with:truncation,pre_count:true,reset_id:true配置使用截断,否??是,但clean_with会立即在调用数据库的位置清理数据库,即在您的情况下的所有测试之前清理一次。但是自动增量在每次测试后都不会重置。好的。。。我不明白。那么更好的方法是,调用clean_,使用:截断。。。在拆卸方法中,或将策略更改为:截断?区别是什么?实际上可能差不多,但标准的方法是制定战略。也就是说,删除带有行的clean_,并将策略设置为:截断。应该是这样。
# 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