やっぱり、テストが重要だろうということでRSpecの本を読んだので、そのまとめ。セットアップはメモしとかないと忘れるのでメモ。
Everyday Rails - RSpecによるRailsテスト入門
RSpecのセットアップ。
環境
- rails 5.1.1
- ruby 2.5.1
- RSpec 3.6
セットアップ
以前はあれこれインストールしなくてはいけませんでしたが、RSpec 3.6
からはかなりシンプルになりました。
rspec-rails
とテストスイートの起動時間を速くするspring-commands-rspec
をインストール。
1
2
3
4
5
6
7
8
9
10
|
Gemfile
group :development, :test do
gem 'rspec-rails', '~> 3.6.0'
gem "factory_bot_rails"
end
group :development do
gem 'spring-commands-rspec'
end
|
Gemfile
に追記後。
binstub
を作成
1
|
$ bundle exec spring binstub rspec
|
テストデータベース
テストデータベースがなければ以下の方法で追加する。
SQLite
1
2
3
4
|
config/database.yml
test:
<<: *default
database: db/test.sqlite3
|
MySQLやPostgreSQL
1
2
3
4
5
|
config/database.yml
test:
<<: *default
database: db/ project_test
`project_test`の部分は自分のアプリケーションにあわせて適切に置き換える
|
次にrakeタスクを実行して接続可能なデータベースの作成。
1
|
$ bin/rails db:create:all
|
RSpecの設定
1
2
3
4
5
6
|
$ bin/rails g rspec:install
Running via Spring preloader in process 2541
create .rspec ← RSpec用の設定ファイル
create spec ← スペックファイルを格納するディレクトリ
create spec/spec_helper.rb ← RSpec用の設定ファイル
create spec/rails_helper.rb
|
Rspecの出力をデフォルトの形式からドキュメント形式へ変更(やらなくてもいい)
1
2
3
|
.rspec
--require spec_helper
--format documentation
|
確認
1
2
3
4
5
|
$ bin/rspec
Running via Spring preloader in process 56846
No examples found.
Finished in 0.00074 seconds (files took 0.144553 seconds to load)
0 examples, 0 failures
|
余計なものが作られないようにジェネレータを設定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module Projects
class Application < Rails::Application
config.load_defaults 5.1
config.generators do |g|
g.test_framework :rspec,
view_specs: false,
helper_specs: false,
routing_specs: false,
request_specs: false
end
end
end
|
モデルスペックの作成
1
|
$ bin/rails g rspec:model user
|
コントローラスペックの作成 コントローラはテストしないことが多い
1
|
$ bin/rails g rspec:controller users
|
アプリケーションにファクトリを追加する
1
|
$ bin/rails g factory_bot:model user
|
フィーチャスペックの作成
1
|
$ bin/rails g rspec:feature users
|
設定終わり。
See Also