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

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

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

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

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Ruby on Rails

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

Q&A

解決済

1回答

1196閲覧

【RSpec】「dependent: destoy」のテストにてエラー:「バリデーションに失敗しました」の解消方法について

otdsh9432

総合スコア55

Ruby on Rails 5

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

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Ruby on Rails

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

0グッド

1クリップ

投稿2020/11/01 07:39

編集2020/11/04 13:28

解決したいこと

rspec実行時、下記のエラーが出てテストが失敗になります。こちらのエラー解決方法についてお伺いしたいです。

ruby

1Failures: 2 1) User dependent: destoy destroys all posts when deleted 3 Failure/Error: 2.times { FactoryBot.create(:post, user: user) } 4 5 ActiveRecord::RecordInvalid: 6 バリデーションに失敗しました: Create userを入力してください

「Create userを入力してください」と出ていますが、
FactoryBotで作成したuserを使っているため、userは作成されていると考えておりました。
アソシエーションを伴うFactoryBotでのテストデータの作成方法が誤っているのではないかと
推測しています。
並行して「アソシエーションを伴うFactoryBotでのテストデータの作成方法」を調べているのですが、エラーの解消方法が見当たらず、お伺いしたい次第です。

現状

ログインユーザの情報を格納するuserモデルの単体テストを実施しようとしています。

<対象テストコード(models/user_spec.rb)>

ruby

1require 'rails_helper' 2 3RSpec.describe User, type: :model do 4 let(:user) { FactoryBot.create(:user) } 5 6 # ユーザID,メール,パスワードがあれば有効な状態であること 7 it "is valid with a email and password" do 8 expect(FactoryBot.build(:user)).to be_valid 9 end 10 11 # 削除の依存関係 12 describe "dependent: destoy" do 13 # 削除すると、紐づく店舗も全て削除されること 14 it "destroys all posts when deleted" do 15 2.times { FactoryBot.create(:post, user: user) } 16 expect { user.destroy }.to change(user.posts, :count).by(-2) 17 end 18 end 19end

テストデータ:FactoryBotの中身

factories/users.rb

ruby

1FactoryBot.define do 2 factory :user do 3 sequence(:email) { |n| "test#{n}@gmail.com" } 4 password { "passwd" } 5 end 6end
factories/posts.rb

ruby

1FactoryBot.define do 2 factory :post do 3 sequence(:title) { |n| "テスト投稿#{n}"} 4 description {"口コミのテストです"} 5 prefecture_code {"1"} 6 rest_type {"1"} 7 association :user 8 association :community 9 end 10end

modelの中身

userモデルでは、post(投稿)などの他のモデルとアソシエーションがあり、
userモデルのレコードが削除されると、それに紐づくpostモデルのレコードも削除されるようになっています。具体的なコードは以下です。

models/user.rb(抜粋)

ruby

1class User < ApplicationRecord 2 devise :database_authenticatable, :registerable, 3 :recoverable, :rememberable, :validatable, :timeoutable, authentication_keys: [:email] 4 validates :email, presence: true, uniqueness: true 5 validates :username, length: { maximum: 30 } 6 has_one_attached :image 7 8 has_many :posts, dependent: :destroy 9 has_many :likes, dependent: :destroy 10 has_many :comments , dependent: :destroy 11 has_many :belongings, dependent: :destroy 12 has_many :applies, dependent: :destroy 13 14 has_many :communities, through: :belongings # ユーザが所属しているコミュニティ 15 16 has_many :follower, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy # フォロー取得 17 has_many :followed, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy # フォロワー取得 18 has_many :following_user, through: :follower, source: :followed # 自分がフォローしている人 19 has_many :follower_user, through: :followed, source: :follower # 自分をフォローしている人 20end
post.rb(抜粋)

ruby

1class Post < ApplicationRecord 2 validates :title, presence: true, length: { maximum:30 } 3 validates :description, presence: true, length: { maximum:200 } 4 validates :prefecture_code, presence: true 5 validates :rest_type, presence: true 6 has_one_attached :image 7 8 belongs_to :user 9 belongs_to :community 10 has_many :likes, dependent: :destroy 11 has_many :comments, dependent: :destroy 12end

試したこと

①user_spec.rbの対象のテストケースの中でcreate userすべきかと考え、
以下のテストコードを記述しましたが、変わらず同じエラーが出ました。

ruby

1 # 削除の依存関係 2 describe "dependent: destoy" do 3 # 削除すると、紐づく店舗も全て削除されること 4 it "destroys all posts when deleted" do 5 post_user = FactoryBot.create(:user) 6 2.times { FactoryBot.create(:post, user: post_user) } 7 expect { post_user.destroy }.to change(post_user.posts, :count).by(-2) 8 end 9 end

②2.timesを辞めて、postは1回のみcreateするようにして-1されるかを見るように修正しても、
全く同じエラーが出るままでした。

③該当テストケースのitの中でPostをcreateする記述に変えると、下記のエラーが出るようになりました。
<user_spec.rb>

ruby

1 # 削除の依存関係 2 describe "dependent: destoy" do 3 # 削除すると、紐づく店舗も全て削除されること 4 it "destroys all posts when deleted" do 5 post_user = FactoryBot.create(:user) 6 Post.create(title: "1"*6, description:"1"*10, rest_type:"1", prefecture_code:"1", user_id:post_user.id) 7 expect { post_user.destroy }.to change(post_user.posts, :count).by(-1) 8 end

<エラー内容>

ruby

1 1) User dependent: destoy destroys all posts when deleted 2 Failure/Error: expect { post_user.destroy }.to change(post_user.posts, :count).by(-1) 3 expected `Post::ActiveRecord_Associations_CollectionProxy#count` to have changed by -1, but was changed by 0

⇒「ユーザを消しても、紐づく投稿が消えなかった」ということかと思いますが、
userのmodelには has_many :posts, dependent: :destroy 、postのモデルには belongs_to :user と記述しています。

申し訳ありませんが、まだRspecを学習し始めたばかりなこともあり、
基本的な箇所で見逃している点等あるかもしれないです。
不明点や追加必要な情報ございましたら、ご教示いただけますと幸いです。
よろしくお願いいたします。

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

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

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

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

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

winterboum

2020/11/03 22:59

Userの作成に失敗しているかも。 Userのvalidationを載せてください。 それと、 models/user_spec にて FactoryでUserが出来ることを確認しておくのも手。
otdsh9432

2020/11/04 13:32 編集

ご確認いただきありがとうございます。 Userのvalidationがわかるよう、app/models/user.rbの抜粋部分を増やして記載しました。 また、models/user_spec に追記し、FactoryでUserが出来ることを確認したところ、Userが正常にできることは確認することができました。
guest

回答1

0

ベストアンサー

可能性は2つあります。
1.Userのemailはuniqueが求められています。botではランダムではなくシーケンス番号が常に1からつく形で作られています。
Userをひとつだけ作る分には成功しますが、何回も呼ばれると同じ番号で作ることになり、失敗することがあります。その失敗したのがFactoryBot.create(:post, user: post_user)で使われている。
このタイミングで post_userを確認してください
2. エラーメッセージとは辻褄合わないのですが
factories/posts.rbで必要なcomunnityが作られていないようです。

投稿2020/11/04 13:59

winterboum

総合スコア23347

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

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

otdsh9432

2020/11/06 14:14 編集

ご指摘の通り、きちんとuserが作られているかの確認のため、一旦、FactoryBotをやめてcreate文でデータを作成してみることにしました。また、作成したデータが有効かを一つずつ確認する記載にし、communityも作るようにしました。 ``` let(:community) { FactoryBot.create(:community) } # 削除の依存関係 describe "dependent: destoy" do before do @user = User.create(email: "temp123@temp.com", password:"password") @com = Community.create(name: "1"*8, create_user_id: @user.id, publish_flg: 1) end it "confirm user create" do expect(@user).to be_valid end it "confirm community create" do expect(@com).to be_valid end it "confirm post create" do expect(FactoryBot.create(:post, user: @user, community: @com)).to be_valid end # 削除すると、紐づくpostも全て削除されること it "destroys all posts when deleted" do FactoryBot.create(:post, user: @user, community: @com) expect { @user.destroy }.to change(@user.posts, :count).by(-1) end end ``` ⇒こうしてみたところ、エラーはなくなりました。
otdsh9432

2020/11/06 14:14 編集

おそらくなのですが、「factories/posts.rbで必要なcomunnityが作られていない」ことが大きな原因だったと考えられます。post作成時にcommunityも入れると、下記の当初の質問時の記述でもテストOKとなりました。 ``` let(:user) { FactoryBot.create(:user) } # 削除の依存関係 describe "dependent: destoy" do before do @com = Community.create(name: "1"*8, create_user_id: user.id, publish_flg: 1) end # 削除すると、紐づくpostも全て削除されること it "destroys all posts when deleted" do 2.times { FactoryBot.create(:post, user: user, community: @com) } expect { user.destroy }.to change(user.posts, :count).by(-2) end end ```
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問