2016-03-25 3 views
1

テスト/ test_helper.rbに自動インクリメントインデックスをリセットしません:DatabaseCleanerは、レールのテストユニット

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 

なぜ機能しないのですか?私のミスはどこですか?

答えて

3

これは予想される動作です。 :transaction戦略を使用してテーブルをクリーンアップしています。これは、各テストがトランザクション後にteardownの間にROLLBACK -edのトランザクション内にラップされることを意味します。

bug #1139を参照してください)あなたは、あなたが使用しているデータベースに述べていないが、ROLLBACKAUTO_INCREMENTをリセットしません、どちらもMySQLでは(bug #6714を参照)やPostgreSQLの中で。

このSO answerに従って私はあなたはあなたのテストでauto_incrementのID値に決して頼るべきではないと思います。私はあなたが予想されるレコードで作業していると主張する代わりに、他の属性をテストするべきだと思います。

AUTO_INCREMENTカウンターを本当にリセットする必要がある場合は、代わりに:truncationクリーニング戦略を使用してください。私。 clean_with行を削除し、戦略を:truncationに設定してください。それはトランザクションよりもはるかに遅いです。

+0

'DatabaseCleaner.clean_with(:truncation、pre_count:true、reset_ids:true)'切り捨てを使用する設定、いいえ?? – Matrix

+0

はい、しかし、 'clean_with'は、呼び出された場所、つまりあなたのケースのすべてのテストの前に一度dbをクリーンアップします。しかし、AUTO_INCREMENTは各テストの後**リセットされません**。 – BoraMa

+0

ok ...私はそれを理解していませんでした。それでは、何が良いのですか?ティアダウンメソッドで 'clean_with(:truncation ...)'を呼び出すか、戦略を切り捨てに変更しますか?違いは何ですか? – Matrix

関連する問題