Module: WCC::Contentful::Test::Factory

Included in:
RSpec
Defined in:
lib/wcc/contentful/test/factory.rb

Instance Method Summary collapse

Instance Method Details

#contentful_create(const, context = nil, **attrs) ⇒ Object

Builds a in-memory instance of the Contentful model for the given content_type. All attributes that are known to be required fields on the content type will return a default value based on the field type.

Raises:

  • (ArgumentError)


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
# File 'lib/wcc/contentful/test/factory.rb', line 10

def contentful_create(const, context = nil, **attrs)
  const = WCC::Contentful::Model.resolve_constant(const.to_s) unless const.respond_to?(:content_type_definition)
  attrs = attrs.transform_keys { |a| a.to_s.camelize(:lower) }

  id = attrs.delete('id')
  sys = attrs.delete('sys')
  raw = attrs.delete('raw') || default_raw(const, id)
  bad_attrs = attrs.reject { |a| const.content_type_definition.fields.key?(a) }
  raise ArgumentError, "Attribute(s) do not exist on #{const}: #{bad_attrs.keys}" if bad_attrs.any?

  raw['sys'].merge!(sys) if sys

  attrs.each do |k, v|
    field = const.content_type_definition.fields[k]

    raw_value = v
    raw_value = to_raw(v, field.type) if %i[Asset Link].include?(field.type)
    raw['fields'][field.name] = raw_value
  end

  instance = const.new(raw, context)

  attrs.each do |k, v|
    field = const.content_type_definition.fields[k]
    next unless %i[Asset Link].include?(field.type)

    unless field.array ? v.any? { |i| i.is_a?(String) } : v.is_a?(String)
      instance.instance_variable_set("@#{field.name}_resolved", v)
    end
  end

  instance
end