2
0

More than 1 year has passed since last update.

【Rails】validateはカスタムメソッド

Posted at

よく使用するvalidatesとめちゃくちゃ似てるカスタムメソッド
モデルの状態を確認し、無効な場合にerrorsコレクションにメッセージを追加するメソッドを作成できる

model.rb
class Invoice < ApplicationRecord
  validate :expiration_date_cannot_be_in_the_past

  private

  def expiration_date_cannot_be_in_the_past
    if expiration_date.present? && expiration_date < Date.today
      errors.add(:expiration_date, ": 過去の日付は使えません")
    end
  end
...
end

RSpecでテストする際

expiration_date_cannot_be_in_the_pastメソッドがprivateだった場合、
モデルの単体テストではなく、リクエストテストで期待するエラーが返るかのテストをする方がよいらしい。

参考

2
0
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
2
0