前提・実現したいこと
マイクロポストを昇順に取り出せるようコードを書いています。
ご教授いただきたいのは'NotNullViolation'エラーがなぜ表示されているのかです。
以下のエラーメッセージの他に同じ内容で52件のエラーが表示されています。
考えてみた結果仮説を立てたのですが私の認識は合っていますでしょうか?
「microposts.user_idがNOT NULL制約により失敗したとあるので以下に添付するfixtureファイル内でuserのIDが無いことが原因。」
お手数ですがよろしくお願いします。
発生している問題・エラーメッセージ
ERROR["test_should_not_allow_the_admin_attribute_to_be_edited_via_the_web", #<Minitest::Reporters::Suite:0x0000000006353e68 @name="UsersControllerTest">, 3.895290147999731] test_should_not_allow_the_admin_attribute_to_be_edited_via_the_web#UsersControllerTest (3.90s) ActiveRecord::NotNullViolation: ActiveRecord::NotNullViolation: RuntimeError: NOT NULL constraint failed: microposts.user_id
該当のソースコード
(micropost_test.rb) require 'test_helper' class MicropostTest < ActiveSupport::TestCase def setup @user = users(:michael) #userに紐付いた新しいmicropostオブジェクトを返す @micropost = @user.microposts.build(content: "Lorem ipsum") end #作成したマイクロポストが有効か確認 test "should be valid" do assert @micropost.valid? end #マイクロポストがuser_idを持つか確認 test "user id should be present" do @micropost.user_id = nil assert_not @micropost.valid? end test "content should be present " do @micropost.content = " " assert_not @micropost.valid? end test "content should be at most 140 characters " do @micropost.content = "a" * 141 assert_not @micropost.valid? end test "order should be most recent first" do assert_equal microposts(:most_recent), Micropost.first end end
(test/fixtures/microposts.yml) orange: content: "I just ate an orange!" created_at: <%= 10.minutes.ago %> tau_manifesto: content: "Check out the @tauday site by @mhartl: http://tauday.com" created_at: <%= 3.years.ago %> cat_video: content: "Sad cats are sad: http://youtu.be/PKffm2uI4dk" created_at: <%= 2.hours.ago %> most_recent: content: "Writing a short test" created_at: <%= Time.zone.now %>
(micropost.rb) class Micropost < ApplicationRecord belongs_to :user #投稿をdescending(降順)にする default_scope -> { order(created_at: :desc) } #descをシンボルにする validates :user_id, presence: true validates :content, presence: true, length: { maximum: 140 } end
試したこと
①タイポが無いかの確認。
②ActiveRecord::NotNullViolationのエラーは初めてだったので検索。
検索の結果Django使用時の同エラーを解決する記事はteratailやstack overflowにて複数読んだのですが、rails使用時の解決を示すページは見つからなかったため質問させていただきました。
補足情報(FW/ツールのバージョンなど)
macOS catalina10.15.2
ruby 2.6.3
rails 6.0.1
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/12 05:17