Rails でアプリを作る② RSpec 導入
テストを書いていきます。今回はRSpecを使用します。以下を Gemfile
に追加してください。
[Gemfile]
group :development, :test do # 省略 gem "rspec-rails" end
% bundle
RSpec を設定する
RSpecをインストールします。
% rails g rspec:install create .rspec create spec create spec/spec_helper.rb create spec/rails_helper.rb
RSpecの出力をドキュメント形式に変更するために、/rspec
を編集します。
[.rspec]
--require spec_helper --format documentation
Railsには、railsコマンド、Rakeコマンド、テストを高速に実行するためのプリローダーであるSpringがデフォルトで付属しています。
Spring is a Rails application preloader. It speeds up development by keeping your application running in the background, so you don't need to boot it every time you run a test, rake task or migration.
binstub
を使用すると、Spring を Rspec で動作させることができます。binstub
を使うには、 gem spring-commands-rspec
を Gemfile
の development
グループに配置する必要があります。Springもコメントアウトされていたのでコメントインしました。
[Gemfile]
group :development do # 省略 gem "spring" gem "spring-commands-rspec" end
% bundle
binstub
を作成します。
% bundle exec spring binstub rspec
* bin/rspec: generated with Spring
アプリケーションの bin
ディレクトリに rspec
という実行ファイルが作成されます。
動作確認をします。
% bin/rspec xxxx/3.0.3/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:101:in `block in preload': Spring reloads, and therefore needs the application to have reloading enabled. Please, set config.cache_classes to false in config/environments/test.rb.
エラーが出ました。Springはアプリケーションでリロードを有効にする必要があるようです。
https://github.com/rails/spring
Please, make sure config.cache_classes is false in the environments that Spring manages. That setting is typically configured in config/environments/*.rb. In particular, make sure it is false for the test environment.
[config/environments/test.rb]
Rails.application.configure do # 省略 config.cache_classes = false # 省略
もう一度動作確認をします。
% bin/rspec DEBUGGER[spring app | kioku | started 7 mins ago | test mode#97048]: Attaching after process 96821 fork to child process 97048 Running via Spring preloader in process 97048 No examples found. Finished in 0.00044 seconds (files took 0.16712 seconds to load) 0 examples, 0 failures
問題なく動作しました。
最後に、rails g
コマンドで同時生成されるファイルを変更します。
[config/application.rb]
# 省略 module Kioku class Application < Rails::Application # 省略 config.generators do |g| g.test_framework :rspec, fixtures: false, view_specs: false, helper_specs: false, routing_spec: false end end end
続きは次回。