Madogiwa Blog

主に技術系の学習メモに使っていきます。

RubyonRails:deviseを導入したらテストが通らなくなってハマったのでメモ

deviseを導入し、userモデルを作成後テストが通らなくなったので、 その事象と対応策をメモしますφ(..)

事象

deviseを導入しuserモデルを作成後、rails test実行時に下記エラーが発生し、テストが通らなくなった。

$ rails test

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_users_on_email"
DETAIL:  Key (email)=() already exists.
: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2017-08-06 23:19:03.809282', '2017-08-06 23:19:03.809282', 298486374)

解決策

userモデル作成時に自動生成されたuser.ymlファイルが原因。 デフォルトで設定値が入っていないため、emailnilが設定されKey重複エラーとなっていた。 そのため、root/app/test/fixtures/user.ymlを削除し、test時にユーザーが作成されないようにしたらエラーが解消した。

user.yml

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
 
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value