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 3 years have passed since last update.

【メモ】RSpecの準備・セットアップ

Posted at

はじめに

RSpecの導入手順を記しとこうと思います。
ここではRSpec, FactoryBotの導入部分を書いていきます。

Gemfileの編集

次の様にGemfileを編集する。

Gemfile
group :development, :test do #すでにあるブロックに下3行を追加
  gem "rspec-rails"
  gem 'spring-commands-rspec'
  gem "factory_bot_rails"
end

自分用(Rubyのバージョンを変えたらエラーが出たため)

Rubyのバージョンが 3.0.0 以上の場合、Gemfileに以下を記入
これを記入しないとrspecコマンドを実行してもエラーが出る。

Gemfile
gem 'rexml', '~> 3.1', '>= 3.1.9'

そしてbundle installする。

RSpecのインストール

コマンドラインで次のコマンドを実行。

rails g rspec:install

次のコードを.rspecファイルに追加。

.rspec
--format documentation

Config/Application.rbの編集

次のコードを追加。

config/application.rb
class Application < Rails::Application
  config.generators do |g|
      g.test_framework :rspec,
        controller_specs: true,
        fixtures: true,
        helper_specs: true,
        model_specs: true,
        request_spec: false,
        routing_specs: false,
        view_specs: false
    end
end

これでRSpecの導入は終了。
以下、RSpecコマンド

・モデルスペック

rails g rspec:model user

・システムスペック

rails g rspec:system projects

FactoryBotの設定

rails_helperを編集。
*必須ではない

rails_helper.rb
RSpec.configure do |config| #元からあるこのブロックに以下の1行を追加
  config.include FactoryBot::Syntax::Methods
end

これがあることで次の様に簡潔にコードか書ける。

# 通常の呼び出し方
user = FactoryBot.create(:user)

# 上のコードを書いたことにより省略形が使える様になる。
user = create(:user)

おわりに

以上で導入完了です。

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?