0
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?

More than 1 year has passed since last update.

rspec-railsとは

Last updated at Posted at 2023-03-12

rspec-railsとは

rubyやrailsの代表的なテストフレームワークで、必要なgemを一つにまとめてインストールしてくれる。

なぜdeveropment環境にも追加するのか

rspec-railsにはファイルを作成するgeneratorがあり、例えばdeveropment環境でコントローラーをgenerateした際に、そのコントローラーに対応するspecテストファイルも一緒に作成してくれて便利だから。

使用するまでの流れ

gemを追加

Gemfile
group :development, :test do
  gem 'rspec-rails'
end
ターミナル
$ bundle install

Rspecをインストール

ターミナル
$ bin/rails generate rspec:install

      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

デフォルトオプションを設定 .rspecファイル

.rspec
--require spec_helper
--format documentation
--warnings

--require spec_helper - spec_helperファイルを呼び出す。
--warnings - アプリや、使用中のgemから出力された警告を全て表示する。
--format documentation - テスト実行中、どのテストがパスし、どのテストが失敗したのかが分かりやすくなる。

  • .rspecファイルで設定したオプションは、コマンドラインで渡すオプションと同じ扱いになる。
ターミナル
$ bundle exec rspec --require spec_helper --format documentation --warnings

ジェネレーターを設定する

rails generateコマンドで自動的に作成されて欲しくないファイルを、config/application.rbファイルで設定できる。

config/application.rb
module Projects
  class Application < Rails::Application
    config.load_defaults 7.0
    config.generators do |g|
      g.test_framework :rspec,
        fixtures: false,
        view_specs: false,
        helper_specs: false,
        routing_specs: false
      g.factory_bot false

    end
  end
end

falseを設定することで、ファイルが自動作成されなくなる。

  • 補足
    なぜview_specsは作成しないのか?
    →信頼性の高いview_specテストをすることは非常に手間がかかるから。Rails開発者の中では、システムスペックを使用することが標準的になっている。

ファイルの命名規則

app/controller/sample_controller.rbの場合
spec/controller/sample_controller_spec.rb

app/helpers/sample_helper.rbの場合
spec/helpers/sample_helper_spec.rb

参考サイト

RailsテストフレームワークRSpecのインストールと基本的な使い方、基礎文法
RSpecの.rspecファイルは # を使ってもコメントアウトされない(のでプルリクを送ってマージされた!)
Everyday Rails - RSpecによるRailsテスト入門

0
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
0
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?