- Gemfile に追加
- バージョンは公式ページを参考に https://github.com/rspec/rspec-rails
group :development, :test do
# 中略
gem 'rspec-rails', '~> 3.8'
end
-
rails generate rspec:install
で初期化- Spec ディレクトリが準備されるので、そこにテストファイルを追加していく
- テストファイルは
users_controller_spec.rb
のような感じで命名。ディレクトリ掘っても良い。
-
テスト用データベースの作成
rails db:test:prepare
bundle exec rails db:migrate RAILS_ENV=test
bundle exec rspec
- 冪等性を保つために、
spec_helper.rb
に以下を追記して実行前にDBをリセットすると良い
config.before(:suite) do
DatabaseRewinder.clean_all
end
- 使用するデータは
SeedFu
を使って都度インサートすると良い。RSpec と相性良さそう - フィルタ機能を使って、使いたいデータだけインサートするようにするともっと良い
fixture_paths = "#{Rails.root}/db/fixtures"
filter = /001_tag/ # path/to/db/fixtures/001_tag.rb
SeedFu.seed(fixture_paths, filter)
- タグを付けると一部のテストのみ実行可能
context 'GET /api/users/1', now: true do
# テスト内容
end
bundle exec rspec -t @now
⚠ 通常のテストコマンドだと実行されない
rails test:system