Skip to content

Instantly share code, notes, and snippets.

@35d
Last active February 26, 2019 15:24
Show Gist options
  • Save 35d/3ba5582967654c828f7a70424d742d77 to your computer and use it in GitHub Desktop.
Save 35d/3ba5582967654c828f7a70424d742d77 to your computer and use it in GitHub Desktop.

インストール

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment