【Rails】minitestで新規投稿ができない
前提
Railsで投稿アプリを開発しています。
ローカルサーバー上では投稿できるのですが、minitestではvalid?メソッドが通りません。
実現したいこと
テストコード
class InfoPostTest < ActionDispatch::IntegrationTest # fixturesで定義したユーザー def setup @michael = users(:michael) end # Green test "user valid?" do @michael.valid? end # Red test "@info valid?" do @info = @michael.infos.build( name: "Michael info name", url: "michael_info.com", address: "michael info address", point: "aaa", genre_id: 1, ) assert @info.valid? # ここがRed end
Infoモデル設計
infoはお店の情報を表します。
id
, name
, url
, address
, point
, user_id
, genre_id
, created_at
, updated_at
のカラムを持っています。
User
, Genre
モデルに紐付いています。
class Info < ApplicationRecord belongs_to :user belongs_to :genre validates :name, {presence: true} validates :address, {presence: true} validates :url, {presence: true} validates :genre_id, {presence: true} validates :point, {presence: true, length: {maximum: 140}} end
UserとGenreのモデル設計
Infoの紐付け元のモデルではhas_many :infos
を指定しています。
Userモデル
class User < ApplicationRecord has_many :infos, dependent: :destroy end
Genreモデル
class Genre < ApplicationRecord has_many :infos, dependent: :destroy end
infos_controllerの設計
infos_controllerのcreate
アクションは下記です。
def create @info = Info.new(info_params) if @info.save redirect_to info_path(@info) else render new_info_path end end private def info_params params.require(:info).permit(:name, :url, :address, :point, :genre_id ).merge(user_id: @current_user.id) end
発生している問題・エラーメッセージ
FAIL["test_@info_valid?", #<Minitest::Reporters::Suite:0x000000012a251c20 @name="InfoPostTest">, 0.5968529999954626] test_@info_valid?#InfoPostTest (0.60s) Expected false to be truthy.
試したこと
-
@info
にcreated_at: 2.hours.ago
を追加 => 解決せず -
@info
にuser_id: @michael.id
を追加 => 解決せず -
build
ではなくnew
に変更 => 解決せず -
コンソールにて
$ user = User.first => 情報が表示される $ info = user.infos.build( $ name: "Michael info name", $ url: "michael_info.com", $ address: "michael info address", $ point: "aaa", $ genre_id: 1 $ ) => #<Info:0x000000013988a308 id: nil, name: "Michael info name", url: "michael_info.com", address: "michael info address", point: "aaa", user_id: 1, genre_id: 1, created_at: nil, updated_at: nil> $ info.valid? => true #ここでvalid?に対してtrueが返ってきているのにminitestだと通らないのが謎 $ info.user.name => "test" # 正しい値を返している
補足情報(FW/ツールのバージョンなど)
ruby -v => ruby 2.6.10p210 (2022-04-12 revision 67958) [arm64-darwin21] rails -v => Rails 5.2.8.1
初めての質問ですので不足している情報もあるかと思いますが、よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。