Railsのテスト用設定(Rails Tutorial 3.6)


Railsチュートリアルのテスト用設定

Railsチュートリアルを進めていて、メモしておきたいテスト用設定があったので、Railsチュートリアル 3.6から引用。

なお、いずれもmasterブランチで行う必要あり。

minitest reporters

Railsのデフォルトのテストで red や green を表示するために以下を追加

test/test_helper.rb
~
require "minitest/reporters"
Minitest::Reporters.use!
~

Guard

ファイルなどを変更すると自動的にテストを実行してくれるツール

gemの取り込み

チュートリアル内でGemfileは追加済みのため割愛

初期化

$ bundle exec guard init

tmuxのインストール(Cloud9利用時のみ)

Guardの通知を有効にするために必要
$ sudo yum install -y tmux

生成されたGuardfileの編集

Guardfileを以下の内容で上書き

# Guardのマッチング規則を定義
guard :minitest, spring: "bin/rails test", all_on_start: false do
  watch(%r{^test/(.*)/?(.*)_test\.rb$})
  watch('test/test_helper.rb') { 'test' }
  watch('config/routes.rb')    { integration_tests }
  watch(%r{^app/models/(.*?)\.rb$}) do |matches|
    "test/models/#{matches[1]}_test.rb"
  end
  watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|
    resource_tests(matches[1])
  end
  watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|
    ["test/controllers/#{matches[1]}_controller_test.rb"] +
    integration_tests(matches[1])
  end
  watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|
    integration_tests(matches[1])
  end
  watch('app/views/layouts/application.html.erb') do
    'test/integration/site_layout_test.rb'
  end
  watch('app/helpers/sessions_helper.rb') do
    integration_tests << 'test/helpers/sessions_helper_test.rb'
  end
  watch('app/controllers/sessions_controller.rb') do
    ['test/controllers/sessions_controller_test.rb',
     'test/integration/users_login_test.rb']
  end
  watch('app/controllers/account_activations_controller.rb') do
    'test/integration/users_signup_test.rb'
  end
  watch(%r{app/views/users/*}) do
    resource_tests('users') +
    ['test/integration/microposts_interface_test.rb']
  end
end

# 与えられたリソースに対応する統合テストを返す
def integration_tests(resource = :all)
  if resource == :all
    Dir["test/integration/*"]  else
    Dir["test/integration/#{resource}_*.rb"]
  end
end

# 与えられたリソースに対応するコントローラのテストを返す
def controller_test(resource)
  "test/controllers/#{resource}_controller_test.rb"
end

# 与えられたリソースに対応するすべてのテストを返す
def resource_tests(resource)
  integration_tests(resource) << controller_test(resource)
end

gitignoreファイルへの追記

Guard使用時のSpringとGitの競合を防ぐために、.gitignoreファイルにspring/ディレクトリを追加
(cloud9の場合、.gitignoreファイルはhiddenファイルとなっている)

# Ignore Spring files.
/spring/*.pid

Guard実行、完了

新しいターミナルで以下コマンドを実行
$ bundle exec guard

その他

Spring killなどの解説もあったが、少し難しいため必要に駆られた際に確認することとした。