delegation_test.rb 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
require 'cases/helper'
require 'models/post'
require 'models/comment'

module ActiveRecord
  class DelegationTest < ActiveRecord::TestCase
    fixtures :posts

    def assert_responds(target, method)
      assert target.respond_to?(method)
      assert_nothing_raised do
12 13 14
        method_arity = target.to_a.method(method).arity

        if method_arity.zero?
15
          target.send(method)
16
        elsif method_arity < 0
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
          if method == :shuffle!
            target.send(method)
          else
            target.send(method, 1)
          end
        else
          raise NotImplementedError
        end
      end
    end
  end

  class DelegationAssociationTest < DelegationTest
    def target
      Post.first.comments
    end

    [:map, :collect].each do |method|
A
Akshay Vishnoi 已提交
35
      test "##{method} is delegated" do
36 37 38 39
        assert_responds(target, method)
        assert_equal(target.pluck(:body), target.send(method) {|post| post.body })
      end

A
Akshay Vishnoi 已提交
40
      test "##{method}! is not delegated" do
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
        assert_deprecated do
          assert_responds(target, "#{method}!")
        end
      end
    end

    [:compact!, :flatten!, :reject!, :reverse!, :rotate!,
      :shuffle!, :slice!, :sort!, :sort_by!].each do |method|
      test "##{method} delegation is deprecated" do
        assert_deprecated do
          assert_responds(target, method)
        end
      end
    end

    [:select!, :uniq!].each do |method|
      test "##{method} is implemented" do
        assert_responds(target, method)
      end
    end
  end

  class DelegationRelationTest < DelegationTest
64 65
    fixtures :comments

66
    def target
67
      Comment.where(body: 'Normal type')
68 69 70
    end

    [:map, :collect].each do |method|
A
Akshay Vishnoi 已提交
71
      test "##{method} is delegated" do
72 73 74 75
        assert_responds(target, method)
        assert_equal(target.pluck(:body), target.send(method) {|post| post.body })
      end

A
Akshay Vishnoi 已提交
76
      test "##{method}! is not delegated" do
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
        assert_deprecated do
          assert_responds(target, "#{method}!")
        end
      end
    end

    [:compact!, :flatten!, :reject!, :reverse!, :rotate!,
      :shuffle!, :slice!, :sort!, :sort_by!].each do |method|
      test "##{method} delegation is deprecated" do
        assert_deprecated do
          assert_responds(target, method)
        end
      end
    end

    [:select!, :uniq!].each do |method|
A
Akira Matsuda 已提交
93
      test "##{method} triggers an immutable error" do
94 95 96 97 98 99 100
        assert_raises ActiveRecord::ImmutableRelation do
          assert_responds(target, method)
        end
      end
    end
  end
end