3
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.

has_secure_password でパスワードの暗号化を行った Rails model のテストデータを fixture で作る

Posted at

概要

has_secure_password でパスワードの暗号化を行う様にした model を使うメソッドを Minitest でテストする為に fixture でテストデータを投入しようしたら、テーブルには password というカラムはありませんというエラーでテストコードが通りませんでした。
fixture で password_digest カラムに暗号化した値を入れてテストデータを作る方法を調べました。
調べるのに時間がかかったので、解決方法を残します。

環境

Rails 6.0.3

モデル

class Hoge < ApplicationRecord
  ...
  has_secure_password
end

エラーになった fixture

hoge_hoge:
  ...
  password: password

出ていたエラー

ActiveRecord::Fixture::FixtureError: table "hoges" has no columns named "password".

原因

fixture では has_secure_password で追加される password アクセサは使えず、 ERB を使って ruby のコードを実行しなければいけなかった様です。

修正した fixture

hoge_hoge:
  ...
  password_digest: <%= BCrypt::Password.create('password') %>

テーブルのカラム名である password_digest に BCrypt::Password.create を使って生成した値を入れています。

参考にさせて頂きました。

(fixtureでpassword_digestに直接暗号化した値を指定する方法 https://stackoverflow.com/questions/30894771/rails-fixtures-with-bcrypt)

(フィクスチャのしくみ https://railsguides.jp/testing.html#%E3%83%95%E3%82%A3%E3%82%AF%E3%82%B9%E3%83%81%E3%83%A3%E3%81%AE%E3%81%97%E3%81%8F%E3%81%BF を参照)

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