aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb
blob: 5af9733a680d35585f877b1c54daa9d90aad5903 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
require "cases/helper"
require 'models/topic'

class I18nGenerateMessageValidationTest < ActiveRecord::TestCase
  def setup
    Topic.reset_callbacks(:validate)
    @topic = Topic.new
    I18n.backend = I18n::Backend::Simple.new
  end

  def reset_i18n_load_path
    @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
    I18n.load_path.clear
    I18n.backend = I18n::Backend::Simple.new
    yield
  ensure
    I18n.load_path.replace @old_load_path
    I18n.backend = @old_backend
  end

  # validates_associated: generate_message(attr_name, :invalid, message: custom_message, value: value)
  def test_generate_message_invalid_with_default_message
    assert_equal 'is invalid', @topic.errors.generate_message(:title, :invalid, :value => 'title')
  end

  def test_generate_message_invalid_with_custom_message
    assert_equal 'custom message title', @topic.errors.generate_message(:title, :invalid, :message => 'custom message %{value}', :value => 'title')
  end

  # validates_uniqueness_of: generate_message(attr_name, :taken, message: custom_message)
  def test_generate_message_taken_with_default_message
    assert_equal "has already been taken", @topic.errors.generate_message(:title, :taken, :value => 'title')
  end

  def test_generate_message_taken_with_custom_message
    assert_equal 'custom message title', @topic.errors.generate_message(:title, :taken, :message => 'custom message %{value}', :value => 'title')
  end

  # ActiveRecord#RecordInvalid exception

  test "RecordInvalid exception can be localized" do
    topic = Topic.new
    topic.errors.add(:title, :invalid)
    topic.errors.add(:title, :blank)
    assert_equal "Validation failed: Title is invalid, Title can't be blank", ActiveRecord::RecordInvalid.new(topic).message
  end

  test "RecordInvalid exception translation falls back to the :errors namespace" do
    reset_i18n_load_path do
      I18n.backend.store_translations 'en', :errors => {:messages => {:record_invalid => 'fallback message'}}
      topic = Topic.new
      topic.errors.add(:title, :blank)
      assert_equal "fallback message", ActiveRecord::RecordInvalid.new(topic).message
    end
  end

  test "translation for 'taken' can be overridden" do
    I18n.backend.store_translations "en", {errors: {attributes: {title: {taken: "Custom taken message" }}}}
    assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => 'title')
  end

end