LoginSignup
0
0

More than 1 year has passed since last update.

RSpec導入で躓いた話

Last updated at Posted at 2022-05-02

概要

既存の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 にアクセスしてこの画面が出たら成功です

スクリーンショット 2022-04-29 16.18.29.png

RSpec導入

Gemfile
+ 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

記事を見てるとこれで上手くいくはずなのに上手くいかない😅

スクリーンショット 2022-05-02 19.40.22.png

解決策

ググるとRuby3.1から昔のデフォルトのGemを依存関係として追加する必要があるとのこと

Gemfile
group :development, :test do
  # 〜 省略 〜
  gem 'rspec-rails'
+ gem 'net-smtp', require: false
end
$ bundle install
$ bundle exec rspec

通ったー😚

次に'factory_bot'導入していく

factory_botは簡単にモデルのインスタンスを作成できる(主にテストで使うらしい)

Gemfile
group :development, :test do
  # 〜 省略 〜
  gem 'rspec-rails'
  gem 'net-smtp', require: false
+ gem 'factory_bot'
end
$ bundle install

テストを通過した文言も表示されるようにする

.rspec
--require spec_helper
--format documentation <--追加

ファイルの作成

spec配下にmodelsフォルダとfactoriesフォルダを作成し、テストしたいモデルのファイルも作成します

spec/models/users_spec.rb
 →テストしたい内容を記述します

spec/models/user.rspec.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
 →ダミーデータを作成します

spec/factories/user.rb
FactoryBot.define do
  factory :user do
    name {"hoge"}
    email {"example@hoge.com"}
    password{"fugafuga"}
  end
end

これでテストを走らせるとエラー

$ bundle exec rspec

スクリーンショット 2022-05-02 20.23.06.png

解決策

どうやら上手くFactoryBotが起動してない様子

"spec/support/factory_bot.rb"を作成する

factory_bot.rbに次の内容を記述する

factory_bot.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

rails_helper.rbで作成したファイルを読み込む

rails_helper.rb
require 'support/factory_bot'

テストを走らせると

$ bundle exec rspec

またエラー🥲
スクリーンショット 2022-05-02 20.28.44.png

解決策

ググるとspec_helper.rbに以下のような記述を追加するとの記事がありました

spec/spec_helper.rb
RSpec.configure do |config|
+  config.before(:all) do
+   FactoryBot.reload
+  end
end

これでテストを走らせると

$ bundle exec rspec

通ったーーーーー😍😍
スクリーンショット 2022-05-02 20.29.13.png

最後に

エラーが出ても落ち着いて対処していきたい。
1人でも多くの人に今回の記事が参考になれば幸いです

0
0
2

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