File: association.rb

package info (click to toggle)
ruby-factory-bot 6.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,372 kB
  • sloc: ruby: 7,827; makefile: 6
file content (58 lines) | stat: -rw-r--r-- 1,429 bytes parent folder | download | duplicates (2)
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
module FactoryBot
  class Declaration
    # @api private
    class Association < Declaration
      def initialize(name, *options)
        super(name, false)
        @options = options.dup
        @overrides = options.extract_options!
        @factory_name = @overrides.delete(:factory) || name
        @traits = options
      end

      def ==(other)
        self.class == other.class &&
          name == other.name &&
          options == other.options
      end

      protected

      attr_reader :options

      private

      attr_reader :factory_name, :overrides, :traits

      def build
        raise_if_arguments_are_declarations!

        [
          Attribute::Association.new(
            name,
            factory_name,
            [traits, overrides].flatten
          )
        ]
      end

      def raise_if_arguments_are_declarations!
        if factory_name.is_a?(Declaration)
          raise ArgumentError.new(<<~MSG)
            Association '#{name}' received an invalid factory argument.
            Did you mean? 'factory: :#{factory_name.name}'
          MSG
        end

        overrides.each do |attribute, value|
          if value.is_a?(Declaration)
            raise ArgumentError.new(<<~MSG)
              Association '#{name}' received an invalid attribute override.
              Did you mean? '#{attribute}: :#{value.name}'
            MSG
          end
        end
      end
    end
  end
end