LoginSignup
0
0

More than 3 years have passed since last update.

rails test で発生する LoadError (cannot load such file -- bcrypt) を解決する (Railsチュートリアル 6章)

Posted at

自分がrailsチュートリアルを進めていく上で、発生したエラーを記録していきます。
ハードはMacBook Air, 開発環境はVScodeを用いています。

Rails チュートリアル 6章 6.3 セキュアなパスワードを追加する

LoadError (cannot load such file -- bcrypt) のエラーが発生するまでのあらすじ

add_password_digest_to_usersというマイグレーションファイルを生成し、データベースでマイグレーションを実行します。

$ rails generate migration add_password_digest_to_users password_digest:string
$ rails db:migrate

Gemfileにbcryptを記述し、$ bundle install を実行します。

Gemfile
gem 'rails',          '5.1.6'
gem 'bcrypt',         '3.1.12'
$ bundle install

次にUserモデル内にhas_secure_passwordを追記します。

app/models/user.rb
class User < ApplicationRecord
  ~省略~
  has_secure_password
end

ここで

$ rails test

を実行すると、has_secure_password によって追加されるバリデーションによってエラーが発生するはずです。

しかし次のようなエラーが発生しました。

$ rails test
LoadError: cannot load such file -- bcrypt
〜省略〜

試しに、rails consoleをして、User.newを実行すると、、、

$ rails console

Running via Spring preloader in process 18909
Loading development environment (Rails 5.1.7)

WARNING: This version of ruby is included in macOS for compatibility with legacy software. 
In future versions of macOS the ruby runtime will not be available by 
default, and may require you to install an additional package.

>User.new
You don't have bcrypt installed in your application. Please add it to your Gemfile and run bundle install
Traceback (most recent call last):
        3: from (irb):1
        2: from app/models/user.rb:1:in `<top (required)>'
        1: from app/models/user.rb:10:in `<class:User>'
LoadError (cannot load such file -- bcrypt)

インストールしたはずのbcryptが全然読み込まれない......(泣)

【Rails】bcryptインストール時の"cannot load such file -- bcrypt_ext"エラー対応【Windows】

この解決策が一番それっぽかったけど、これでも全然解決しない、、、、というような状況の人は、次の解決策を試してみてください。

解決方法 Rubyをアップデートする

まず、

$ rbenv versions

でrubyのバージョンを確認します。
次に、そのrubyをuninstallsimasu

$ rbenv uninstall 確認したバージョン

次に、新しいバージョンを指定して、インストールします。(ここでは2.6.5)

$ rbenv install 2.6.5

インストールが完了したら次を実行します。

$ rbenv global 2.6.5
$ rbenv rehash

これでrubyのバージョンが変わっているはずです。($ ruby -vで確認できる)

参考:rbenvの使い方と仕組みについて

最後に、Gemfileの内容を変更・確認します。

source 'https://rubygems.org'

ruby '2.6.5'  ←追記
gem 'bcrypt' ←バージョンも指定しなくて良い(bcrypt-rubyとかもmacOSならいらない)

▲ここでは、rubyのバージョンを指定し、bcryptをバージョン指定なしで最新版をインストールできるように記述します。

$ gem list bcrypt
を実行し、bcryptが入っていたら、
$ gem uninstall bcrypt)
を実行して削除しておく。

bundle installをして、bcryptをインストールします。

$ bundle install

すると、$ rails consoleを実行したときの、WARNINGが解消され、無事エラーが解決します。


役に立ったら是非LGTMボタンをポチッと押していただけると嬉しいです。
一緒に Rails学習 頑張りましょう!:raised_hand_tone1:

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