1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RSpecの初期セットアップと便利な設定

Last updated at Posted at 2025-03-30

RSpec のセットアップ

Gemfile に rspec を追加

以下の gem を追加して、bundle install を実行。
rspec-rails には rspec-core とその他の独立した gem が含まれている。

group :development, :test do
  gem 'rspec-rails' end
end

テストデータベースを作成

config/database.yml
test:
  <<: *default
  database: db/test.sqlite3

上記のように設定(されていることを確認)し、以下コマンドでテストデータベースを作成。

すでに作成済みなら、rails タスクはテストデータベースがすでにあることをちゃんと教えてくれるので、既存のデータベースを間違って消してしまう心配はいらない。

$ bin/rails db:create:all

RSpec の設定

以下コマンドで RSpec の設定ファイルを生成。

$ bin/rails generate rspec:install

以下のファイルが作成されたことがターミナルに表示される。

  create  .rspec                 # RSpecの設定ファイル
  create  spec                   # テストファイルのディレクトリ
  create  spec/spec_helper.rb    # RSpecの動きをカスタマイズするヘルパーファイル
  create  spec/rails_helper.rb   # 上記と同じ

テストを実行(bundle exec rspec)し、以下のようなメッセージが表示されれば設定は完了。

  no examples found  # テストが作成されてないときのメッセージ

RSpec の出力をドキュメント形式に変更

以下のように .rspec を編集することで RSpec の出力をデフォルトの形式から読みやすいドキュメント形式に変更できる。

.rspec
--require spec_helper
--format documentation
  • テストスイートの実行中にどのスペックがパスし、どのスペックが失敗したのかがわかりやすくなる
  • スペックのアウトラインが美しく出力
  • 出力を仕様書のように使える

rspec binstub を使って短いコマンドで実行できるようにする

通常の RSpec の実行はbundle exec rspecとなるが、rspec binstub を使うとbin/rspecという短いコマンドで実行できるようになる。
以下のコマンドで binstub を生成。bin ディレクトリ内に rspec という名前の実行用ファイルが作成される。

$ bundle binstubs rspec-core

ジェネレータの設定

rails generate コマンドを実行してモデルやコントローラーを作成すると、RSpec のファイルを spec ディレクトリに同時に作成できる。
RSpec をインストールしたことで、もともとデフォルトだった Minitest のファイルは test ディレクトリに作成されなくなり、RSpec のファイルが spec ディレクトリに作成されるようになる。
デフォルトの設定だと、不要なスペックが作成されることがあるので、好みで以下のように設定を変更できる。

config/application.rb
config.generators do |g|
  g.test_framework :rspec,
    fixtures: false,       # テストDBにレコードを作成するファイルの作成をスキップ
    view_specs: false,     # ビューのテストファイルの作成をスキップ
    helper_specs: false,   # ヘルパーのテストファイルの作成をスキップ
    routing_specs: false   # ルーティングのテストファイルの作成をスキップ
  g.factory_bot false      # factory_botのファイルの作成をスキップ
end

--pretend (-p) オプションを使用して実際に何が生成されるかを確認することができる

rails generate controller admin/campaigns/descriptions -p

spec ファイルの命名規則

app/helpers/projects_helper.rb >> spec/helpers/projects_helper_spec.rb

lib/my_library.rb >> spec/my_library_spec.rb

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?