Module: WCC::Contentful::Test::Double

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

Instance Method Summary collapse

Instance Method Details

#contentful_double(const, **attrs) ⇒ Object

Builds a rspec double 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)


12
13
14
15
16
17
18
19
20
# File 'lib/wcc/contentful/test/double.rb', line 12

def contentful_double(const, **attrs)
  const = WCC::Contentful::Model.resolve_constant(const.to_s) unless const.respond_to?(:content_type_definition)
  attrs.symbolize_keys!

  bad_attrs = attrs.reject { |a| const.instance_methods.include?(a) }
  raise ArgumentError, "Attribute(s) do not exist on #{const}: #{bad_attrs.keys}" if bad_attrs.any?

  double(attrs[:name] || attrs[:id] || nil, defaults(const).merge(attrs))
end

#contentful_image_double(**attrs) ⇒ Object

Builds an rspec double of a Contentful image asset, including the file URL and details. These fields can be overridden.



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
63
64
65
66
67
68
69
# File 'lib/wcc/contentful/test/double.rb', line 25

def contentful_image_double(**attrs)
  attrs = {
    title: WCC::Contentful::Test::Attributes[:String],
    description: WCC::Contentful::Test::Attributes[:String],
    file: {
      url: '//images.ctfassets.net/7yx6/2rak/test.jpg',
      details: {
        image: {
          width: 0,
          height: 0
        }
      }
    }
  }.deep_merge!(attrs)

  attrs[:file] = OpenStruct.new(attrs[:file]) if attrs[:file]

  attrs[:raw] = {
    sys: {
      space: {
        sys: {
          type: 'Link',
          linkType: 'Space',
          id: ENV.fetch('CONTENTFUL_SPACE_ID', nil)
        }
      },
      id: SecureRandom.urlsafe_base64,
      type: 'Asset',
      createdAt: Time.now.to_formatted_s(:iso8601),
      updatedAt: Time.now.to_formatted_s(:iso8601),
      environment: {
        sys: {
          id: 'master',
          type: 'Link',
          linkType: 'Environment'
        }
      },
      revision: rand(100),
      locale: 'en-US'
    },
    fields: attrs
  }

  double(attrs)
end