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

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

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

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

Ruby on Rails

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

Q&A

0回答

789閲覧

Rspec accepts_nested_attributes_forのバリデーションテスト

whakapapa-HTML

総合スコア0

RSpec

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

Ruby on Rails

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

0グッド

0クリップ

投稿2021/08/27 04:26

編集2021/08/27 04:30

質問内容

accepts_nested_attributes_forでネストしたサブクラスのバリデーションテストはどのように書けばいいでしょうか。
レシピを投稿する際、proceduresとingredientsを一緒に投稿できるようにしています。

Recipeファクトリー

FactoryBot.define do factory :recipe do association :user association :genre name {"レシピ"} introduction {"レシピ紹介"} serving {"1"} recipe_image { Rack::Test::UploadedFile.new(File.join(File.join(Rails.root, '/spec/fixtures/images/test.jpg'))) } after(:build) do |built_recipe| built_recipe.procedures << build(:procedure, recipe: built_recipe) end after(:build) do |built_recipe| built_recipe.ingredients << build(:ingredient, recipe: built_recipe) end end end

Recipe.rb

class Recipe < ApplicationRecord include ActiveModel::Dirty has_many :reviews, dependent: :destroy has_many :bookmarks, dependent: :destroy has_many :ingredients, dependent: :destroy has_many :procedures, dependent: :destroy belongs_to :user, optional: true belongs_to :genre attr_accessor :recipe_image_cache mount_uploader :recipe_image, RecipeImageUploader accepts_nested_attributes_for :ingredients, :procedures, allow_destroy: true with_options presence: true do validates :serving validates :name validates :recipe_image validates :introduction validates :ingredients end

Ingredient.rb

class Ingredient < ApplicationRecord belongs_to :recipe with_options presence: true do validates :name validates :amount end end

該当のコード

recipe_spec.rb

it "材料名が空欄の場合、無効となる" do recipe = build(:recipe) #ここでingrdientのnameが空欄の場合以下の結果をテストしたい。 expect(ingreedient.errors[:name]).to include("が入力されていません。") end

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問