質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

2回答

1741閲覧

rails testが通らない

takuo5

総合スコア48

Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

1クリップ

投稿2019/12/24 08:49

編集2020/01/05 04:27

前提・実現したいこと

railsで作成したアプリケーションにtestを実装していますが下記エラーが出てtestが実行できません。

登録したアカウントでE-mailが同じものがあるのでエラーが出たのかと思い、rails db:resetを実行してから試したのですが同じ結果でした。
どのように改善すべきでしょうか。

発生している問題・エラーメッセージ

Error: ArticlesControllerTest#test_should_get_show: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: column email is not unique: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2019-12-24 08:33:36.597587', '2019-12-24 08:33:36.597587', 298486374)

 articles_controller_test.rb

require 'test_helper' class ArticlesControllerTest < ActionDispatch::IntegrationTest test "should get index" do get articles_index_url assert_response :success end test "should get show" do get articles_show_url assert_response :success end test "should get edit" do get articles_edit_url assert_response :success end test "should get new" do get articles_new_url assert_response :success end end

 routes.rb

Rails.application.routes.draw do devise_for :users, :controllers => { :registrations => 'users/registrations', :sessions => 'users/sessions' } resources :articles root "articles#index" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end

 user.rb

class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_one :profile, dependent: :destroy has_many :articles, dependent: :destroy delegate :name, to: :profile end

 articles.yml

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: title: MyString body: MyText two: title: MyString body: MyText

 database.yml

# SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: db/test.sqlite3 production: <<: *default database: db/production.sqlite3

 test.sqlite3

SQLite format 3@   -�)���  ���<���k�)tablearticlesarticlesCREATE TABLE "articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "body" text, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "user_id" integer, "image_id" varchar)P++Ytablesqlite_sequencesqlite_sequenceCREATE TABLE sqlite_sequence(name,seq)p?�indexindex_articles_on_user_idarticlesCREATE INDEX "index_articles_on_user_id" ON "articles" ("user_id")�]� tableprofilesprofilesCREATE TABLE "profiles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id" integer, "name" varchar DEFAULT '' NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)p?�indexindex_profiles_on_user_idprofilesCREATE INDEX "index_profiles_on_user_id" ON "profiles" ("user_id") ��k�W� tableusersusersCREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar DEFAULT '' NOT NULL, "encrypted_password" varchar DEFAULT '' NOT NULL, "reset_password_token" varchar, "reset_password_sent_at" datetime, "remember_created_at" datetime, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)e5� indexindex_users_on_emailusers CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")�S�Gindexindex_users_on_reset_password_tokenusers CREATE UNIQUE INDEX "index_users_on_reset_password_token" ON "users" ("reset_password_token")   �������)20191204031155)20191202103026)20191204030243)20191204152522)20191204022005)20191205081943 �������)20191204031155)20191202103026)20191204030243)20191204152522)20191204022005) 20191205081943 ��QH#AAenvironmenttest2019-12-25 12:08:45.7202332019-12-25 12:08:45.727612 ��# environment ))���x //�tableschema_migrationsschema_migrations CREATE TABLE "schema_migrations" ("version" varchar NOT NULL PRIMARY KEY)A U/indexsqlite_autoindex_schema_migrations_1schema_migrations �N 55�?tablear_internal_metadataar_internal_metadataCREATE TABLE "ar_internal_metadata" ("key" varchar NOT NULL PRIMARY KEY, "value" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)G [5indexsqlite_autoindex_ar_internal_metadata_1ar_internal_metadata

 schema.rb

ActiveRecord::Schema.define(version: 20191205081943) do create_table "articles", force: :cascade do |t| t.string "title" t.text "body" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" t.string "image_id" t.index ["user_id"], name: "index_articles_on_user_id" end create_table "profiles", force: :cascade do |t| t.integer "user_id" t.string "name", default: "", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["user_id"], name: "index_profiles_on_user_id" end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end end

 test_helper.rb

ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all Add more helper methods to be used by all tests here... end

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

補足情報(FW/ツールのバージョンなど)

AWS Cloud9

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

rails db:reset で developmentはresetされたが testは元のまま
の可能性があります
RAIL_ENV=test rails db:reset  してみてください

ああ、判った
INSERT INTO "users" ("created_at", "updated_at", "id")
ってありますね。emailを指定していないので nil という値が入り、二人目から衝突します。
テストcodeにはテストに用いるデータの準備が書かれていません。
準備しているところの codeを追加してください

投稿2019/12/24 09:13

編集2019/12/25 12:46
winterboum

総合スコア23329

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

takuo5

2019/12/25 12:17

ご提案いただきました、RAIL_ENV=test rails db:resetを試したあとにrais testを実行しましたが、全く同じエラーが表示されました。
winterboum

2019/12/25 12:53

回答追記しました
takuo5

2019/12/26 04:32

申し訳ございません、理解力がなくてわからないのですが。 それぞれのtestにemail = ~という形でtestに使うための仮のEmailアドレスを記述すればよいということでしょうか?
winterboum

2019/12/26 05:09

ということですが、今テストデータどうやって初期化しているか見せていただけると助言できるかも
takuo5

2019/12/26 06:13

テストデータではなく、rails db:resetで実際のアプリケーションに登録してあるデータをリセットしてました。 テストデータは上記のarticles.ymlに書かれているものだと思いますが、これにEmailアドレスを追加すれば解消できるという意味でしょうか?
winterboum

2019/12/26 07:50 編集

articlesではないですね、エラーが起きたのが INSERT INTO "users"  ですから。 このUserへのinsertがどのタイミングで、どのデータを元に行われたのか、がわからないと助言不能です。 実際のアプリケーションでつかうdatabaseとテストで使うdatabaseは別物ですから、テストの方のデータの初期化がわからないと
takuo5

2019/12/29 06:04 編集

返信遅れてしまいまして申し訳ありません。 ということはテスト用のデータベースの中身を見るとどのようにtestデータが処理されたかわかるということでしょうか? そもそもtest用にデータ・ベースを作成した記憶がないのですが、これは作る必要があるのか、それかデフォルトでどこかにあるのでしょうか? 教えていただけると幸いです。
winterboum

2019/12/29 08:09

config/database.yml見せていただけますか?
takuo5

2019/12/30 12:27

database.ymlを追加しました。
winterboum

2019/12/30 14:46

test: がありますね。そこの情報で作られています
takuo5

2019/12/31 04:14

ありがとうございます。 test.sqlite3を追加しました。 読んでみましたが何がどの様になっているのかわかりません。どこの部分を読むべきでしょうか。 唯一わかるのは何かが作成された日付等がかかれているぶぶんだけなのですが、、、
winterboum

2019/12/31 04:18

「test.sqlite3を追加しました。」 とは?
takuo5

2019/12/31 10:04

database.ymlの 'test: ' 以下に 'database: db/test.sqlite3'と書かれているのでtest用のデータ・ベースは'test.sqlite3'ということだと思ったのですが間違ってますでしょうか? ですのでその中身を上記の情報に追加しておきました。 このファイルからなにか今回のエラー解決の糸口は見つかりますでしょうか? 年末なのにご対応いただき本当にありがとうございます。
winterboum

2019/12/31 10:38

ああ、そういうことですか。了解。 「そもそもtest用にデータ・ベースを作成した記憶がないのですが、これは作る必要があるのか、それかデフォルトでどこかにあるのでしょうか?」 という質問があったので、database.ymlに定義してありますね、って指摘したのです。 で、 testデータベースにデータの初期化をどこでもやっていない? ではエラーメッセージにある「 INSERT INTO "users"」はどこで実行指示しているんでしょう? それがわからないと解決策が見えない。 テストに関わるファイル全部中身出してください
takuo5

2019/12/31 12:27

申し訳ありません。testのファイルが多すぎてすべて載せることができないそうです。 しかしながら、teetファイルの中身すべて確認しましたが 'INSERT INTO "users" 'を指示しているコードは見つかりませんでした。 schema.rbというファイルにデータ・ベース関係の記述がされているのを見つけましたがこちらは関係ないでしょうか?
winterboum

2019/12/31 12:34

'test_helper' は元のママですか、手を入れてますか?入れてたら見せてください。 test/fixtures に userなにがはありますか?有ったら見せてください
takuo5

2020/01/05 04:28

test_helperとusers.ymlは上記のようになっています。 test_helperは何も編集はしていないと思います。
winterboum

2020/01/05 06:28

users.yml にある二つのデータが両方共空データになっています。 このため nil という email になって重複になったのかな、とおもわれます。 このふたつ削除してみてください。 それで駄目だったら、私の智慧を越えています。
takuo5

2020/01/05 09:01

ありがとうございます。 users.ymlの2つのデータを削除すると上記のエラーが消えました。 これですすめることができます。 年末から連日色々と助けていただきありがとうございました。
guest

0

User modelのところにemailのバリデーションでuniquenessの設定をしていますか?
一意性が確保できていないのではないでしょうか

投稿2019/12/24 08:56

story_aniki

総合スコア197

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

takuo5

2019/12/25 12:15

user.rbの情報を上記に追加しました。 見たところemailのバリデーションらしき記述はしていません。 書き記事の③の記述を追加してrails testを再度試してみましたが結果は同じでした。 https://qiita.com/aiorange19/items/6f7d1d0f7582b5159b65
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問