質問内容
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
あなたの回答
tips
プレビュー