Ruby on Rails開発のインターン (Day 18)
こんにちは、皆さん!
ついに今週もラスト1日!
昨日に引き続き、職場のプログラムでcapybaraテストが実行できるようにエラーの原因を探そうと思う。
- トピック:
- 疑問:
- 問題:
- capybaraテストが職場のプログラムで実行されない (解決した)
- 学習した内容:
- テストの時に新しく追加されたデータを自動的に削除する方法
- 今後やってみたいこと:
- Railsの'will-paginate'についてもっと学習する
- リソース:
Railsでdatabase cleanerを使う方法
この目的のためにとても便利なジェムがある。そして、使い方も簡単。2ステップで完了。
***ここではRspecの場合だけについて言及する。CucumberとMinitestユーザーの方々すいません。***
最初に、ジェムのインストール。Gemfile
に下記のを入れて、 bundle install
コマンドを打ってください。
group :test do gem 'database_cleaner' end
これをテストのグループに入れたのは同じデータをキープするためにデータベースのお掃除をするのはテスト環境の時だけでいいからだ。
次に、データベースお掃除の設定を書いていく。これは簡単で基本的には下記のをspec/spec_helper.rb
ファイルに入れればよい。
RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end end
この設定はdb/seeds.rb
の状態に還元するというものだ。つまり、新しく追加されたデータのみが削除されるということだ。 これは便利!!
おまけ:
もし、capybaraテストも使っているのなら、上記に挙げた設定の代わりに、下記のものを使った方がいい。capybaraテストで作ったデータがテストされる前に削除されてしまう可能性があり、エラーの原因になりかねないからだ。
***必ずrequire 'capybara/rspec'
の後に下記のを入れてください!***
RSpec.configure do |config| config.use_transactional_fixtures = false config.before(:suite) do if config.use_transactional_fixtures? raise(<<-MSG) Delete line `config.use_transactional_fixtures = true` from rails_helper.rb (or set it to false) to prevent uncommitted transactions being used in JavaScript-dependent specs. During testing, the app-under-test that the browser driver connects to uses a different database connection to the database connection used by the spec. The app's database connection would not be able to access uncommitted transaction data setup over the spec's database connection. MSG end DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, type: :feature) do # :rack_test driver's Rack app under test shares database connection # with the specs, so continue to use transaction strategy for speed. driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test unless driver_shares_db_connection_with_specs # Driver is probably for an external browser with an app # under test that does *not* share a database connection with the # specs, so use truncation strategy. DatabaseCleaner.strategy = :truncation end end config.before(:each) do DatabaseCleaner.start end config.append_after(:each) do DatabaseCleaner.clean end end
まとめ
ご精読ありがとうございました。では、また次回まで✌