-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
factories.rb
124 lines (105 loc) · 3.07 KB
/
factories.rb
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
require "json_matchers/payload"
require_relative "./support/fake_response"
require_relative "./support/fake_schema"
FactoryBot.define do
factory :response, class: FakeResponse do
skip_create
trait :location do
body { { "latitude": 1, "longitude": 1 } }
end
trait :invalid_location do
body { { "latitude": "1", "longitude": "1" } }
end
initialize_with do
body = attributes.fetch(:body, nil)
json = attributes.except(:body)
payload = JsonMatchers::Payload.new(body || json)
FakeResponse.new(payload.to_s)
end
end
factory :schema, class: FakeSchema do
sequence(:name) { |n| "json_schema-#{n}" }
trait :invalid do
json { "" }
end
trait :location do
json do
{
"id": "file:/#{name}.json#",
"description": "An object containing some #{name} data",
"type": "object",
"required": ["latitude", "longitude"],
"properties": {
"latitude": {
"type": "number",
},
"longitude": {
"type": "number",
},
},
"additionalProperties": false,
}
end
end
trait(:locations) { location }
trait :array_of do
initialize_with do
schema_body_as_json = attributes.fetch(:json, nil)
schema_body = attributes.except(:json, :name)
FakeSchema.new(name, {
"type": "array",
"items": schema_body_as_json || schema_body,
})
end
end
trait :referencing_locations do
association :items, factory: [:schema, :location]
initialize_with do
FakeSchema.new(name, {
"$schema": "https://json-schema.org/draft-04/schema#",
"type": "array",
"items": { "$ref": "file:/#{items.name}.json#" },
})
end
end
trait :referencing_definitions do
association :items, factory: [:schema, :location], name: "location"
association :example, factory: [:response, :location]
transient do
plural { items.name.pluralize }
end
json do
{
"$schema": "https://json-schema.org/draft-04/schema#",
"id": "file:/#{name}.json#",
"type": "object",
"definitions": {
plural => {
"type": "array",
"items": { "$ref": "file:/#{items.name}.json#" },
"description": "A collection of #{plural}",
"example": example,
},
},
"required": [plural],
"properties": {
plural => {
"$ref": "#/definitions/#{plural}",
},
},
}
end
end
initialize_with do
schema_body_as_json = attributes.fetch(:json, nil)
schema_body = attributes.except(:json, :name)
FakeSchema.new(name, schema_body_as_json || schema_body)
end
to_create do |schema|
path = JsonMatchers.path_to_schema(schema.name)
payload = JsonMatchers::Payload.new(schema.json)
path.dirname.mkpath
IO.write(path, payload)
end
end
end