LoginSignup
1
1

More than 5 years have passed since last update.

example.metadataを使って、テストごとにDatabaseCleaner.strategyを切り替える

Last updated at Posted at 2016-05-09

DatabaseCleaner.strategy = :transactionでレコードを削除していると、ROLLBACKとSAVEPOINTを使ってレコードの作成、削除を行う。
その際に作成されるレコードはindexが作成されないため、FULLTEXT searchでの検索に引っかからないなどによってテストが通らない。
そのため、DatabaseCleaner.strategy = :truncationに設定する必要があるのだが、:truncationを使うと実際にレコードを登録してしまうため:trusaction`に比べると実行時間が長くなってしまう。

そこで、必要な箇所だけmetadataで経由で:truncation:transactionを制御するようにしました。

metadataでDatabaseCleaner.strategyを切り替える

spec_helper.rb

RSpec.configure do |config|

  ## 各種設定

  config.use_transactional_fixtures = false

  config.before(:each) do |example|

    DatabaseCleaner.strategy = example.metadata[:cleaner] || :transaction
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

あとはテスト側で、下記のようにcleanerの種類を指定することで一部分のみ:trucationに設定することができます。

  describe 'search hoge', cleaner: :truncation do

  end

参考記事

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1