概要
既存のRailsプロジェクトにRSpecを導入したらつまづいたので解決方法を共有します
1人でも多くの人の役にたてればと思います。
はじめに
使用する環境
- MacOS(M1)
- Rails 6.1.5
- Ruby 3.1.0
- yarn 1.22.17
- Homebrew 3.4.8
はじめにアプリケーションを作成するディレクトリを作成
$ mkdir rails_RSpec_app
$ cd rails_RSpec_app
railsプロジェクトの作成
$ rails new rails_RSpec_app
プロジェクトへ移動
$ cd rails_RSpec_app
サーバー起動
$ rails s
http://localhost:3000 にアクセスしてこの画面が出たら成功です
RSpec導入
+ group :development, :test do
# 〜 省略 〜
gem 'rspec-rails'
end
$ bundle install
$ rails g rspec:install
これでRSpecの導入は終わりなのでモデルを作成していく
$ rails g model user name:string email:string password:string
データベースに反映
$ rails db:migrate
テストを起動
$ bundle exec rspec
記事を見てるとこれで上手くいくはずなのに上手くいかない😅
解決策
ググるとRuby3.1から昔のデフォルトのGemを依存関係として追加する必要があるとのこと
group :development, :test do
# 〜 省略 〜
gem 'rspec-rails'
+ gem 'net-smtp', require: false
end
$ bundle install
$ bundle exec rspec
通ったー😚
次に'factory_bot'導入していく
factory_botは簡単にモデルのインスタンスを作成できる(主にテストで使うらしい)
group :development, :test do
# 〜 省略 〜
gem 'rspec-rails'
gem 'net-smtp', require: false
+ gem 'factory_bot'
end
$ bundle install
テストを通過した文言も表示されるようにする
--require spec_helper
--format documentation <--追加
ファイルの作成
spec配下にmodelsフォルダとfactoriesフォルダを作成し、テストしたいモデルのファイルも作成します
spec/models/users_spec.rb
→テストしたい内容を記述します
require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
it "全ての項目の入力が存在すれば登録できること" do
user = build(:user)
expect(user).to be_valid
end
end
end
spec/factories/user.rb
→ダミーデータを作成します
FactoryBot.define do
factory :user do
name {"hoge"}
email {"example@hoge.com"}
password{"fugafuga"}
end
end
これでテストを走らせるとエラー
$ bundle exec rspec
解決策
どうやら上手くFactoryBotが起動してない様子
"spec/support/factory_bot.rb"を作成する
factory_bot.rbに次の内容を記述する
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
rails_helper.rbで作成したファイルを読み込む
require 'support/factory_bot'
テストを走らせると
$ bundle exec rspec
解決策
ググるとspec_helper.rbに以下のような記述を追加するとの記事がありました
RSpec.configure do |config|
+ config.before(:all) do
+ FactoryBot.reload
+ end
end
これでテストを走らせると
$ bundle exec rspec
最後に
エラーが出ても落ち着いて対処していきたい。
1人でも多くの人に今回の記事が参考になれば幸いです