delegation_test.rb 2.5 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5
require "cases/helper"
require "models/post"
require "models/comment"
6 7

module ActiveRecord
8
  module DelegationTests
9
    ARRAY_DELEGATES = [
10
      :+, :-, :|, :&, :[], :shuffle,
R
Rafael Mendonça França 已提交
11
      :all?, :collect, :compact, :detect, :each, :each_cons, :each_with_index,
12
      :exclude?, :find_all, :flat_map, :group_by, :include?, :length,
13 14
      :map, :none?, :one?, :partition, :reject, :reverse, :rotate,
      :sample, :second, :sort, :sort_by, :slice, :third, :index, :rindex,
15
      :to_ary, :to_set, :to_xml, :to_yaml, :join,
16
      :in_groups, :in_groups_of, :to_sentence, :to_formatted_s, :as_json
17 18 19
    ]

    ARRAY_DELEGATES.each do |method|
20
      define_method "test_delegates_#{method}_to_Array" do
21
        assert_respond_to target, method
22 23
      end
    end
24 25 26 27

    def test_not_respond_to_arel_method
      assert_not_respond_to target, :exists
    end
28 29
  end

30
  class DelegationAssociationTest < ActiveRecord::TestCase
31
    include DelegationTests
32

33
    def target
34
      Post.new.comments
35
    end
36
  end
37

38
  class DelegationRelationTest < ActiveRecord::TestCase
39
    include DelegationTests
40

41 42
    def target
      Comment.all
43 44
    end
  end
45 46 47 48 49 50 51 52

  class QueryingMethodsDelegationTest < ActiveRecord::TestCase
    QUERYING_METHODS = [
      :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :none?, :one?,
      :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, :third_to_last, :third_to_last!, :second_to_last, :second_to_last!,
      :first_or_create, :first_or_create!, :first_or_initialize,
      :find_or_create_by, :find_or_create_by!, :create_or_find_by, :create_or_find_by!, :find_or_initialize_by,
      :find_by, :find_by!,
53
      :destroy_all, :delete_all, :update_all, :delete_by, :destroy_by,
54 55 56 57 58
      :find_each, :find_in_batches, :in_batches,
      :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :left_joins, :left_outer_joins, :or,
      :where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly, :extending,
      :having, :create_with, :distinct, :references, :none, :unscope, :merge,
      :count, :average, :minimum, :maximum, :sum, :calculate,
59
      :pluck, :pick, :ids, :reselect,
60 61 62 63 64 65 66 67 68 69 70 71 72
    ]

    def test_delegate_querying_methods
      klass = Class.new(ActiveRecord::Base) do
        self.table_name = "posts"
      end

      QUERYING_METHODS.each do |method|
        assert_respond_to klass.all, method
        assert_respond_to klass, method
      end
    end
  end
73
end