LoginSignup
24
26

More than 5 years have passed since last update.

has_manyなオブジェクトの上限数を設定&テストする

Posted at

この記事ではBlog::Post#tagsの数を5つまでに制限する場合のサンプルコードを紹介します。

元記事は「Rails4でhas_manyな関連オブジェクトの上限数を設定&テストする」です。

まずモデル側でpost_tagsLengthValidationを設定します。

app/models/blog/post.rb
class Blog::Post < ActiveRecord::Base
  MAX_POST_TAGS_LENGTH = 5

  has_many :post_tags
  has_many :tags, through: :post_tags

  validates :post_tags, length: {maximum: MAX_POST_TAGS_LENGTH}
end

続いてロケール設定を追加します。

config/locale/models/blog/post/ja.yml
ja:
  activerecord:
    errors:
      models:
        blog/post:
          attributes:
            post_tags:
              too_long: 'は%{count}個までしか登録できません'
    models:
      blog/post: ブログ記事
    attributes:
      blog/post:
        id: 管理ID
        post_tags: タグ

次はテストを追加します。

spec/models/blog/post_spec.rb
describe Blog::Post, type: :model do
  context 'with validations' do
    it do
      should validate_objects_length_of(:post_tags).
               is_at_most(Blog::Post::MAX_POST_TAGS_LENGTH).
               with_message("タグは#{Blog::Post::MAX_POST_TAGS_LENGTH}個までしか登録できません")
    end
  end
end

さらっとvalidate_objects_length_ofマッチャを使っていますが、こちらはカスタムマッチャなので元記事のvalidate_objects_length_ofのコードをご覧ください。

24
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
26