validation_test.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. require "test_helper"
  3. class ValidationTest < ActiveSupport::TestCase
  4. test "validation" do
  5. setting = Setting.find_or_initialize_by(var: "host")
  6. assert_equal false, setting.valid?
  7. assert_equal 1, setting.errors.size
  8. assert_errors_on setting, :host, "Host can't be blank"
  9. setting.value = "https://ruby-china.org"
  10. assert_equal true, setting.valid?
  11. assert_equal 0, setting.errors.size
  12. setting = Setting.find_or_initialize_by(var: "user_limits")
  13. assert_equal false, setting.valid?
  14. assert_equal 2, setting.errors.size
  15. assert_errors_on setting, :user_limits, ["User limits can't be blank", "User limits must be numbers"]
  16. setting.value = "hello"
  17. assert_equal false, setting.valid?
  18. assert_errors_on setting, :user_limits, ["User limits must be numbers"]
  19. setting.value = "100"
  20. assert_equal true, setting.valid?
  21. assert_equal 0, setting.errors.size
  22. setting = Setting.find_or_initialize_by(var: "mailer_provider")
  23. assert_equal false, setting.valid?
  24. assert_equal 2, setting.errors.size
  25. assert_errors_on setting, :mailer_provider, ["Mailer provider can't be blank", "Mailer provider is not included in the list"]
  26. setting.value = "hello"
  27. assert_equal false, setting.valid?
  28. assert_equal 1, setting.errors.size
  29. assert_errors_on setting, :mailer_provider, ["Mailer provider is not included in the list"]
  30. setting.value = "smtp"
  31. assert_equal true, setting.valid?
  32. assert_equal 0, setting.errors.size
  33. end
  34. test "validation with assignment" do
  35. assert_raise_with_validation_message("Validation failed: Host can't be blank") do
  36. Setting.host = ""
  37. end
  38. assert_nothing_raised do
  39. Setting.host = "foo"
  40. end
  41. assert_raise_with_validation_message("Validation failed: Mailer provider is not included in the list") do
  42. Setting.mailer_provider = "foo"
  43. end
  44. assert_nothing_raised do
  45. Setting.host = "smtp"
  46. end
  47. end
  48. end
  49. def assert_raise_with_validation_message(message)
  50. ex = assert_raise(ActiveRecord::RecordInvalid) { yield }
  51. assert_equal message, ex.message
  52. end