rspec-graphql_response 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 67d1e0d86474c6b5f5e99c3d19e3d1645fe35819d5a47a4fd7007af9c9a5700e
4
+ data.tar.gz: d27339cca95c74fdb174fa0ca6a43116039b449e0b22ef6397ccd76e8eb472d1
5
+ SHA512:
6
+ metadata.gz: b427ec094b4a8e19865e3d610a14abb32625189f7ea190ca61dbcde61e8582abca4464980e2790bb2d30b8ecbb83912034f4a95bcc1cd8744410328a646ad755
7
+ data.tar.gz: d0864628a5e6beb9096fe8901f67dd6f75d824af26631e1b66ea97894bd30da4061f6ceb25ffc692461a1e54a50f7e7c56405f89cce6275e919d624c9dd29dc8
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.pryrc ADDED
@@ -0,0 +1,7 @@
1
+ if defined?(PryByebug)
2
+ Pry.commands.alias_command 'c', 'continue'
3
+ Pry.commands.alias_command 'e', 'exit'
4
+ Pry.commands.alias_command 'f', 'finish'
5
+ Pry.commands.alias_command 'n', 'next'
6
+ Pry.commands.alias_command 's', 'step'
7
+ end
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.6.6
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.6
7
+ before_install: gem install bundler -v 1.17.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at [testdouble.com](https://testdouble.com). All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in rspec-graphql_response.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,48 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rspec-graphql_response (0.1.0)
5
+ rspec
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ byebug (11.1.3)
11
+ coderay (1.1.3)
12
+ diff-lcs (1.4.4)
13
+ graphql (1.12.4)
14
+ method_source (1.0.0)
15
+ pry (0.14.0)
16
+ coderay (~> 1.1)
17
+ method_source (~> 1.0)
18
+ pry-byebug (3.8.0)
19
+ byebug (~> 11.0)
20
+ pry (~> 0.10)
21
+ rake (13.0.3)
22
+ rspec (3.10.0)
23
+ rspec-core (~> 3.10.0)
24
+ rspec-expectations (~> 3.10.0)
25
+ rspec-mocks (~> 3.10.0)
26
+ rspec-core (3.10.1)
27
+ rspec-support (~> 3.10.0)
28
+ rspec-expectations (3.10.1)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.10.0)
31
+ rspec-mocks (3.10.2)
32
+ diff-lcs (>= 1.2.0, < 2.0)
33
+ rspec-support (~> 3.10.0)
34
+ rspec-support (3.10.2)
35
+
36
+ PLATFORMS
37
+ ruby
38
+
39
+ DEPENDENCIES
40
+ bundler (~> 1.17)
41
+ graphql (~> 1.12)
42
+ pry
43
+ pry-byebug
44
+ rake
45
+ rspec-graphql_response!
46
+
47
+ BUNDLED WITH
48
+ 1.17.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Test Double, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,220 @@
1
+ # Rspec::GraphQLResponse
2
+
3
+ RSpec::GraphQLResponse provides a series of RSpec matchers, helper methods, and other configuration to help simplify
4
+ the testing of responses from the `graphql-ruby` gem and the `<GraphQLSchemaName>.execute` method.
5
+
6
+ ## Installation
7
+
8
+ Your app must have `graphql-ruby` and `rspec`. With that done, add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'rspec-graphql_response'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install rspec-graphql_response
21
+
22
+ ## Full Documentation
23
+
24
+ The full documentation for RSpec::GraphQLResponse can be found in the `/docs`
25
+ folder.
26
+
27
+ Custom Matchers:
28
+ * [have_errors matcher](/docs/have_errors.md) - validates errors, or lack of, on
29
+ the GraphQL response
30
+
31
+ Helper Methods:
32
+ * [operation](/docs/operation.md) - retrieves the results of a named operation
33
+ from the GraphQL response
34
+
35
+ Internal API / Development
36
+
37
+ * [.add_matcher](/docs/add_matcher.md) - add a custom RSpec matcher to the
38
+ GraphQLResponse matchers
39
+ * [.add_validator](/docs/add_validator.md) - add a custom validator to be used
40
+ by the custom matchers
41
+
42
+ ## Configuration
43
+
44
+ To get things rolling, add a configuration block to your `spec_helper.rb` (or other file that gets included in specs, as
45
+ desired). Within this block, you'll need to provide the GraphQL Schema to use for query execution.
46
+
47
+ ```ruby
48
+ RSpec::GraphQLResponse.configure |config| do
49
+
50
+ config.graphql_schema = MyGraphQLSchema
51
+
52
+ end
53
+ ```
54
+
55
+ ## Getting Started
56
+
57
+ There are a number of built-in helper methods and matchers that will allow you to skip the copy & paste work of executing
58
+ a GraphQL Schema `.execute`. These include:
59
+
60
+ Spec types:
61
+
62
+ * `type: :graphql`
63
+
64
+ Helper methods:
65
+
66
+ * `execute_graphql`
67
+ * `response`
68
+ * `operation`
69
+
70
+ Matchers:
71
+
72
+ * `have_errors`
73
+
74
+ ### The `:graphql` Spec Type
75
+
76
+ To use these custom helpers and matchers, you need to specificy `type: :graphql` as part of your spec's description. For exmaple,
77
+
78
+ ```ruby
79
+ RSpec.describe Some::Thing, type: :graphql do
80
+
81
+ # ...
82
+
83
+ end
84
+ ```
85
+
86
+ With this `type` set, your specs will have access to all of the `RSpec::GraphQLResponse` code.
87
+
88
+ ### Helper Methods
89
+
90
+ Executing a GraphQL call from RSpec is not the most challening code to write:
91
+
92
+ ```ruby
93
+ let(:query) do
94
+ <<-GQL
95
+ query ListCharacters{
96
+ characters {
97
+ id
98
+ name
99
+ }
100
+ }
101
+ GQL
102
+ end
103
+
104
+ subject do
105
+ MySchema.execute(query)
106
+ end
107
+
108
+ it "does something" do
109
+ response = subject.to_h
110
+
111
+ # expect(response) ...
112
+ end
113
+ ```
114
+
115
+ But copy & paste is often considered a design error, and this code is likely going to be littered throughout your spec files.
116
+
117
+ #### Use the Built-In `execute_graphql`
118
+
119
+ To help reduce the copy & paste, `RSpec::GraphQLResponse` has a built-in `execute_graphql` method that looks for a `query` variable
120
+ in your specs.
121
+
122
+ ```ruby
123
+ RSpec.describe Some::Thing, type: :graphql do
124
+ let(:query) do
125
+ <<-GQL
126
+ query ListCharacters{
127
+ characters {
128
+ id
129
+ name
130
+ }
131
+ }
132
+ GQL
133
+ end
134
+
135
+ it "executes the query" do
136
+ response = execute_graphql.to_h
137
+
138
+ # expect(response) ...
139
+ end
140
+ end
141
+ ```
142
+
143
+ #### Use the Built-In `response`
144
+
145
+ The reduction in code is good, but the copy & paste of `response = execute_graphql.to_h` will quickly become an issue in the same
146
+ way. The reduce this, `RSpec::GraphQLResponse` provides a built-in `response` helper.
147
+
148
+ ```ruby
149
+ RSpec.describe Some::Thing, type: :graphql do
150
+ let(:query) do
151
+ <<-GQL
152
+ query {
153
+ characters {
154
+ id
155
+ name
156
+ }
157
+ }
158
+ GQL
159
+ end
160
+
161
+ it "executes the query" do
162
+ expect(response).to include(
163
+ "data" => {
164
+ "characters" => { ... }
165
+ }
166
+ )
167
+ end
168
+ end
169
+ ```
170
+
171
+ #### Retrieve operation results with `operation`
172
+
173
+ Now that the GraphQL query has been executed and a response has been obtained, it's time to check for the results of a GraphQL
174
+ operation. In the previous example, the spec is expecting to find `data` with `characters` in the response hash. To reduce the
175
+ nested hash checking, use the built-in `operation` method to retrieve the `characters`:
176
+
177
+ ```ruby
178
+ RSpec.describe Some::Thing, type: :graphql do
179
+ let(:query) do
180
+ <<-GQL
181
+ query {
182
+ characters {
183
+ id
184
+ name
185
+ }
186
+ }
187
+ GQL
188
+ end
189
+
190
+ it "executes the query" do
191
+ characters = operation(:characters)
192
+
193
+ expect(characters).to include(
194
+ # ...
195
+ )
196
+ end
197
+ end
198
+ ```
199
+
200
+ Note the lack of `response` use here. Internally, the `operation` method uses the `response` to obtain the data requested. This
201
+ means the entire chain of operations from executing the GraphQL request, to converting the response into a hash, and digging
202
+ through the results to find the correction operation, has been handled behind the scenes.
203
+
204
+ ## Development
205
+
206
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
207
+
208
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
209
+
210
+ ## Contributing
211
+
212
+ Bug reports and pull requests are welcome on GitHub at https://github.com/testdouble/rspec-graphql_response. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
213
+
214
+ ## License
215
+
216
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
217
+
218
+ ## Code of Conduct
219
+
220
+ Everyone interacting in the Rspec::GraphQLResponse project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/testdouble/rspec-graphql_response/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "graphql_response"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/rspec ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'rspec' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ require "pathname"
12
+ ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
13
+ Pathname.new(__FILE__).realpath)
14
+
15
+ bundle_binstub = File.expand_path("../bundle", __FILE__)
16
+
17
+ if File.file?(bundle_binstub)
18
+ if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
19
+ load(bundle_binstub)
20
+ else
21
+ abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
22
+ Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
23
+ end
24
+ end
25
+
26
+ require "rubygems"
27
+ require "bundler/setup"
28
+
29
+ load Gem.bin_path("rspec-core", "rspec")
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,48 @@
1
+ # Adding RSpec Matchers
2
+
3
+ RSpec::GraphQLResponse provides a thin layer around RSpec's native `matcher`
4
+ syntax to ensure the matchers you are adding will be included correctly.
5
+
6
+ This is usefurl whether you are developing new matchers to be included in
7
+ this gem directly, or adding them to your application for your specific needs.
8
+
9
+ ## RSpec::GraphQLResponse.add_matcher
10
+
11
+ To add a new matcher, call `RSpec::GraphQLResponse.add_matcher`.
12
+
13
+ ```ruby
14
+ RSpec::GraphQLResponse.add_matcher do |some_option|
15
+ # ... this is a standard RSpec `matcher` block
16
+ # where you can do anything you would do in RSpec
17
+
18
+ match :foo_bar do
19
+ # do your validation here
20
+ end
21
+ end
22
+ ```
23
+
24
+ This call is only a wrapper around RSpec's `matcher`. For information on how to
25
+ build your matcher, see the [RSpec project documentation](https://relishapp.com/rspec/rspec-expectations/v/3-10/docs/custom-matchers/define-a-custom-matcher).
26
+
27
+ ## Combined with a Custom Validator
28
+
29
+ RSpec::GraphQLResponse provides a means of keeping your matcher code clean while
30
+ also making it easy to unit test the logic and messages supplied from the
31
+ matcher, using [RSpec::GraphQLResponse.add_validator](/docs/add_validator.md).
32
+
33
+ Once a validator has been created, it can be called from a matcher.
34
+
35
+ ```ruby
36
+ RSpec::GraphQLResponse.add_matcher :foo_bar do
37
+ match do |response|
38
+ have_errors = RSpec::GraphQLResponse.validator(:foo_bar)
39
+ @result = have_errors.validate
40
+ end
41
+
42
+ failure_message do |response|
43
+ @result.reason
44
+ end
45
+ end
46
+ ```
47
+
48
+ For information on creating a valdator, see the [add validators documentation](/docs/add_validator.md).
@@ -0,0 +1,10 @@
1
+ # Adding Validators
2
+
3
+ Adding your own matcher is well [documented by the RSpec project](https://relishapp.com/rspec/rspec-expectations/v/3-10/docs/custom-matchers/define-a-custom-matcher).
4
+ What this documentation doesn't cover, however, is unit testing and cleanly
5
+ organizing your matcher code.
6
+
7
+ To solve this, RSpec::GraphQLResponse introduced validators - code that is
8
+ called to manage the validation of a graphql response, and provide the failure
9
+ messages. Validators allow your code to be well organized, and unit tested,
10
+ while providing a clean implementation of the matcher, as shown here:
@@ -0,0 +1,127 @@
1
+ # Using the `have_errors` Matcher
2
+
3
+ The `have_errors` matchers will verify the presence of errors in a graphql
4
+ execution's response. This matcher provides both `.to` and `.not_to` matching
5
+ and messages for all options.
6
+
7
+ ## Basic Use
8
+
9
+ Check for the presence of `response["errors"]`
10
+
11
+ ```ruby
12
+ it "should have errors" do
13
+ expect(response).to have_errors
14
+ end
15
+ ```
16
+
17
+ Ensure there are no errors in the `response`
18
+
19
+ ```ruby
20
+ it "should not have errors" do
21
+ expect(response).to_not have_errors
22
+ end
23
+ ```
24
+
25
+ ## Specify Error Count
26
+
27
+ Check for a specific number of errors, and fail if the response does not have
28
+ that number of errors.
29
+
30
+ ```ruby
31
+ it "should have 3 errors" do
32
+ expect(response).to have_errors(3)
33
+ end
34
+ ```
35
+
36
+ Ensure the response does not have a specific number of errors.
37
+
38
+ ```ruby
39
+ it "should not have 2 errors" do
40
+ expect(response).to_not have_errors(2)
41
+ end
42
+ ```
43
+
44
+ ### CAUTION: False Positives
45
+
46
+ Using `.to have_errors(count)` and especially using `.to_not have_errors(count)` is
47
+ potentially dangerous!
48
+
49
+ Your test may be ensuring there are not 2 errors, but the underlying code may fail
50
+ for an unknown reason and provide a false positive, saying the test passed because
51
+ there was only one error.
52
+
53
+ ## Specify Error Messages
54
+
55
+ When checking for errors, it's best to check for specific messages. This ensures
56
+ the errors are what you expected and not something else, helping to prevent
57
+ false positives in your tests.
58
+
59
+ ### Verify Specific Message
60
+
61
+ ```ruby
62
+ it "raises User not found" do
63
+ expect(response).to have_errors.with_messages("User not found")
64
+ end
65
+ ```
66
+
67
+ This will ensure the `response["errors"]` contains a "User not found" error message.
68
+
69
+ ### Ensure Specifed Error Not Found
70
+
71
+ ```ruby
72
+ it "does not raise User not found" do
73
+ expect(response).to_not have_errors.with_messages("User not found")
74
+ end
75
+ ```
76
+
77
+ ### Fails if Specified Error Found in Array
78
+
79
+ The `.to_not` form of `.with_messages` will ensure that none of the error messages
80
+ specified are found withing the response.
81
+
82
+ If, for example the response looks like this:
83
+
84
+ ```
85
+ {
86
+ "errors" => [
87
+ {"message" => "User not found"},
88
+ {"message" => "Invalid ID format"}
89
+ ]
90
+ }
91
+ ```
92
+
93
+ a test like this would fail:
94
+
95
+ ```ruby
96
+ it "looks for specific errors" do
97
+ expect(response).to_not have_errors.with_messages("User not found", "Some other errors")
98
+ end
99
+ ```
100
+
101
+ The resulting failure message would state that it was expecting not to find the
102
+ "User not found" message, but it was found. The other non-matching error
103
+ messages would be ignored.
104
+
105
+ ### CAUTION: False Positives
106
+
107
+ Using `.to_not have_errors.with_messages("Some Message")` is a good way to
108
+ ensure your code is not throwing a specific error message. However, it should
109
+ not be the only expectation against the response. If your code raises any errors
110
+ other than the ones specified, it will result in a passing test but a response
111
+ that still contains errors.
112
+
113
+ ## Combining Count and Specified Messages
114
+
115
+ The above count and specified messages can be combined in some interesting and
116
+ potentially useful ways.
117
+
118
+ ### Check for a Count with a Message
119
+
120
+ ```ruby
121
+ it "does interesting things" do
122
+ expect(response).to have_errors(1).with_messages("User not found")
123
+ end
124
+ ```
125
+
126
+ This example will ensure there is only 1 error, and that it is "User not found".
127
+ This is by far the most accurate way to check for errors, using this matcher.
data/docs/operation.md ADDED
@@ -0,0 +1,38 @@
1
+ # Using the `operation` helper
2
+
3
+ The `operation` helper will dig through a response to find a data
4
+ structure that looks like,
5
+
6
+ ```ruby
7
+ {
8
+ "data" => {
9
+ operation_name
10
+ }
11
+ }
12
+ ```
13
+
14
+ ## Basic Use
15
+
16
+ ```ruby
17
+ it "has characters" do
18
+ characters = operation(:characters)
19
+
20
+ expect(character).to include(
21
+ { id: 1, name: "Jam" },
22
+ # ...
23
+ )
24
+ end
25
+ ```
26
+
27
+ ## Handling Nil
28
+
29
+ If there is no `"data"` or no named operation for the name supplied, the
30
+ `operation` helper will return `nil`
31
+
32
+ ```ruby
33
+ it "returns nil if operation doesn't exist" do
34
+ character = operation(:something_that_does_not_exist)
35
+
36
+ expect(operation).to be_nil
37
+ end
38
+ ```
@@ -0,0 +1,29 @@
1
+ require "RSpec"
2
+
3
+ require_relative "graphql_response/version"
4
+ require_relative "graphql_response/configuration"
5
+ require_relative "graphql_response/validators"
6
+ require_relative "graphql_response/matchers"
7
+ require_relative "graphql_response/helpers"
8
+
9
+ module RSpec
10
+ module GraphQLResponse
11
+ def self.configure(&block)
12
+ return if block.nil?
13
+
14
+ block.call(configuration)
15
+ end
16
+
17
+ def self.configuration
18
+ @configuration ||= Configuration.new
19
+ end
20
+
21
+ def self.reset_configuration
22
+ @configuration = nil
23
+ end
24
+ end
25
+
26
+ RSpec.configure do |config|
27
+ config.include RSpec::GraphQLResponse, :type => :graphql
28
+ end
29
+ end
@@ -0,0 +1,7 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ class Configuration
4
+ attr_accessor :graphql_schema, :graphql_query_attribute
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,23 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ def self.add_helper(name, &helper)
4
+ helper_module = Module.new do |mod|
5
+ mod.define_method(name) do |*args|
6
+ @result ||= self.instance_exec(*args, &helper)
7
+ end
8
+ end
9
+
10
+ RSpec.configure do |config|
11
+ config.after(:each) do
12
+ helper_module.instance_variable_set(:@result, nil)
13
+ end
14
+ end
15
+
16
+ self.include(helper_module)
17
+ end
18
+ end
19
+ end
20
+
21
+ require_relative "helpers/operation"
22
+ require_relative "helpers/response"
23
+ require_relative "helpers/execute_graphql"
@@ -0,0 +1,4 @@
1
+ RSpec::GraphQLResponse.add_helper :execute_graphql do
2
+ config = RSpec::GraphQLResponse.configuration
3
+ config.graphql_schema.execute(query)
4
+ end
@@ -0,0 +1,5 @@
1
+ RSpec::GraphQLResponse.add_helper :operation do |name|
2
+ return nil unless response.is_a? Hash
3
+
4
+ response.dig("data", name.to_s)
5
+ end
@@ -0,0 +1,3 @@
1
+ RSpec::GraphQLResponse.add_helper :response do
2
+ execute_graphql.to_h
3
+ end
@@ -0,0 +1,14 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ def self.add_matcher(name, &matcher)
4
+ matcher_module = Module.new do |mod|
5
+ extend RSpec::Matchers::DSL
6
+ matcher(name, &matcher)
7
+ end
8
+
9
+ self.include(matcher_module)
10
+ end
11
+ end
12
+ end
13
+
14
+ require_relative "matchers/have_errors"
@@ -0,0 +1,37 @@
1
+ RSpec::GraphQLResponse.add_matcher :have_errors do |count = nil|
2
+ match do |response|
3
+ have_errors = RSpec::GraphQLResponse.validator(:have_errors)
4
+
5
+ @result = have_errors.validate(
6
+ response,
7
+ expected_count: count,
8
+ expected_messages: @messages
9
+ )
10
+
11
+ @result.valid?
12
+ end
13
+
14
+ failure_message do |response|
15
+ @result.reason
16
+ end
17
+
18
+ match_when_negated do |response|
19
+ have_errors = RSpec::GraphQLResponse.validator(:have_errors)
20
+
21
+ @result = have_errors.validate_negated(
22
+ response,
23
+ expected_count: count,
24
+ expected_messages: @messages
25
+ )
26
+
27
+ @result.valid?
28
+ end
29
+
30
+ failure_message_when_negated do |response|
31
+ @result.reason
32
+ end
33
+
34
+ chain :with_messages do |*messages|
35
+ @messages = messages
36
+ end
37
+ end
@@ -0,0 +1,20 @@
1
+ require_relative "validators/validation_result"
2
+ require_relative "validators/validation_base"
3
+ require_relative "validators/validation_runner"
4
+
5
+ module RSpec
6
+ module GraphQLResponse
7
+ def self.add_validator(name, &validator)
8
+ @validators ||= {}
9
+
10
+ validator_class = Class.new(Validators::ValidationBase, &validator)
11
+ @validators[name] = validator_class
12
+ end
13
+
14
+ def self.validator(name)
15
+ @validators[name].new
16
+ end
17
+ end
18
+ end
19
+
20
+ require_relative "validators/have_errors"
@@ -0,0 +1,70 @@
1
+ RSpec::GraphQLResponse.add_validator :have_errors do
2
+ failure_message :nil, "Cannot evaluate nil for errors"
3
+ failure_message :none, "Expected response to have errors, but found none"
4
+ failure_message :unmatched, ->(expected, actual) { "Expected\n\t#{expected.inspect}\nbut found\n\t#{actual.inspect}" }
5
+ failure_message :length, ->(expected, actual) { "Expected response to have #{expected} errors, but found #{actual}" }
6
+
7
+ validate do |response, expected_messages: nil, expected_count: nil|
8
+ next fail_validation(:nil) if response.nil?
9
+
10
+ errors = response.fetch("errors", [])
11
+ actual_messages = errors.map {|e| e["message"] }
12
+
13
+ next fail_validation(:none, actual_messages) if errors.length == 0
14
+
15
+ with_messages = Array(expected_messages).length > 0
16
+ with_count = !expected_count.nil?
17
+
18
+ if with_count
19
+ actual_count = errors.length
20
+ next fail_validation(:length, expected_count, actual_count) if expected_count != actual_count
21
+ end
22
+
23
+ if with_messages
24
+ unmatched_messages = expected_messages.difference(actual_messages)
25
+
26
+ next fail_validation(:unmatched, expected_messages, actual_messages) if unmatched_messages.any?
27
+ end
28
+
29
+ pass_validation
30
+ end
31
+
32
+ failure_message :negated_nil, "Cannot evaluate nil for errors"
33
+ failure_message :negated_none, ->(actual) { "Expected response not to have errors, but found\n\t#{actual.inspect}" }
34
+ failure_message :negated_unmatched, ->(expected, actual) { "Expected not to find any of\n\t#{expected.inspect}\nbut found\n\t#{actual.inspect}" }
35
+ failure_message :negated_length, ->(expected, actual, messages) { "Expected response not to have #{expected} errors, but found #{actual}\n\t#{messages.inspect}" }
36
+
37
+ validate_negated do |response, expected_messages: nil, expected_count: nil|
38
+ next fail_validation(:negated_nil) if response.nil?
39
+
40
+ errors = response.fetch("errors", [])
41
+ actual_messages = errors.map {|e| e["message"] }
42
+ actual_count = errors.length
43
+
44
+ with_messages = Array(expected_messages).length > 0
45
+ with_count = !expected_count.nil?
46
+
47
+ if !with_count && !with_messages && actual_count != 0
48
+ next fail_validation(:negated_none, actual_messages)
49
+ end
50
+
51
+ if with_count
52
+ if expected_count == actual_count
53
+ next fail_validation(:negated_length, expected_count, actual_count, actual_messages)
54
+ elsif !with_messages
55
+ next pass_validation
56
+ end
57
+ end
58
+
59
+ if with_messages
60
+ unmatched_messages = expected_messages & actual_messages
61
+ next fail_validation(:negated_unmatched, expected_messages, unmatched_messages) if unmatched_messages.any?
62
+ end
63
+
64
+ if with_messages || with_count
65
+ next pass_validation
66
+ end
67
+
68
+ pass_validation
69
+ end
70
+ end
@@ -0,0 +1,40 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ module Validators
4
+ class ValidationBase
5
+ class << self
6
+ def failure_message(type, msg)
7
+ @messages ||= {}
8
+ @messages[type] = msg
9
+ end
10
+
11
+ def validate(&validate_method)
12
+ @validate_method = validate_method
13
+ end
14
+
15
+ def validate_negated(&validate_negated_method)
16
+ @validate_negated_method = validate_negated_method
17
+ end
18
+ end
19
+
20
+ def validate(response, *args)
21
+ validate_method = self.class.instance_variable_get(:@validate_method)
22
+
23
+ runner = ValidationRunner.new(self)
24
+ runner.instance_exec(response, *args, &validate_method)
25
+ end
26
+
27
+ def validate_negated(response, *args)
28
+ validate_negated_method = self.class.instance_variable_get(:@validate_negated_method)
29
+
30
+ runner = ValidationRunner.new(self)
31
+ runner.instance_exec(response, *args, &validate_negated_method)
32
+ end
33
+
34
+ def failure_message(type)
35
+ self.class.instance_variable_get(:@messages)[type]
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,35 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ module Validators
4
+ class ValidationResult
5
+ def self.pass
6
+ self.new(true)
7
+ end
8
+
9
+ def self.fail(reason, args)
10
+ self.new(false, reason, args)
11
+ end
12
+
13
+ def valid?
14
+ @is_valid
15
+ end
16
+
17
+ def reason
18
+ if @reason.is_a? Proc
19
+ @reason = @reason.call(*@args)
20
+ end
21
+
22
+ @reason
23
+ end
24
+
25
+ private
26
+
27
+ def initialize(is_valid, reason = nil, args = [])
28
+ @is_valid = is_valid
29
+ @reason = reason
30
+ @args = args
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,25 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ module Validators
4
+ class ValidationRunner
5
+ attr_reader :validator
6
+
7
+ def initialize(validator)
8
+ @validator = validator
9
+ end
10
+
11
+ protected
12
+
13
+ def fail_validation(type, *args)
14
+ message = validator.failure_message(type)
15
+ ValidationResult.fail(message, args)
16
+ end
17
+
18
+ def pass_validation
19
+ ValidationResult.pass
20
+ end
21
+
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,5 @@
1
+ module RSpec
2
+ module GraphQLResponse
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,35 @@
1
+ lib = File.expand_path("../lib/rspec/", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+
4
+ root = File.expand_path("../lib/rspec/graphql_response/", __FILE__)
5
+ $LOAD_PATH.unshift(root) unless $LOAD_PATH.include?(root)
6
+
7
+ require_relative "lib/rspec/graphql_response/version"
8
+
9
+ Gem::Specification.new do |spec|
10
+ spec.name = "rspec-graphql_response"
11
+ spec.version = RSpec::GraphQLResponse::VERSION
12
+ spec.authors = ["River Lynn Bailey"]
13
+ spec.email = ["riverl.bailey@testdouble.com"]
14
+
15
+ spec.summary = %q{Verify ruby-graphql responses with a :graphql spec type}
16
+ spec.description = %q{Adds a :graphql rspec type with built-in helpers and matchers for ruby-graphql gem responses}
17
+ spec.homepage = "https://github.com/testdouble/rspec-graphql_response"
18
+ spec.license = "MIT"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.17"
29
+ spec.add_development_dependency "graphql", "~> 1.12"
30
+ spec.add_development_dependency "rake", ">= 12.0"
31
+ spec.add_development_dependency "pry", "~> 0.14"
32
+ spec.add_development_dependency "pry-byebug", "~> 3.8"
33
+
34
+ spec.add_runtime_dependency "rspec", "~>3.10"
35
+ end
metadata ADDED
@@ -0,0 +1,161 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rspec-graphql_response
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - River Lynn Bailey
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-02-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.17'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
27
+ - !ruby/object:Gem::Dependency
28
+ name: graphql
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.12'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.12'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '12.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '12.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '0.14'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '0.14'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry-byebug
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.8'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.8'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.10'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.10'
97
+ description: Adds a :graphql rspec type with built-in helpers and matchers for ruby-graphql
98
+ gem responses
99
+ email:
100
+ - riverl.bailey@testdouble.com
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - ".pryrc"
107
+ - ".rspec"
108
+ - ".ruby-version"
109
+ - ".travis.yml"
110
+ - CODE_OF_CONDUCT.md
111
+ - Gemfile
112
+ - Gemfile.lock
113
+ - LICENSE.txt
114
+ - README.md
115
+ - Rakefile
116
+ - bin/console
117
+ - bin/rspec
118
+ - bin/setup
119
+ - docs/add_matcher.md
120
+ - docs/add_validator.md
121
+ - docs/have_errors.md
122
+ - docs/operation.md
123
+ - lib/rspec/graphql_response.rb
124
+ - lib/rspec/graphql_response/configuration.rb
125
+ - lib/rspec/graphql_response/helpers.rb
126
+ - lib/rspec/graphql_response/helpers/execute_graphql.rb
127
+ - lib/rspec/graphql_response/helpers/operation.rb
128
+ - lib/rspec/graphql_response/helpers/response.rb
129
+ - lib/rspec/graphql_response/matchers.rb
130
+ - lib/rspec/graphql_response/matchers/have_errors.rb
131
+ - lib/rspec/graphql_response/validators.rb
132
+ - lib/rspec/graphql_response/validators/have_errors.rb
133
+ - lib/rspec/graphql_response/validators/validation_base.rb
134
+ - lib/rspec/graphql_response/validators/validation_result.rb
135
+ - lib/rspec/graphql_response/validators/validation_runner.rb
136
+ - lib/rspec/graphql_response/version.rb
137
+ - rspec-graphql_response.gemspec
138
+ homepage: https://github.com/testdouble/rspec-graphql_response
139
+ licenses:
140
+ - MIT
141
+ metadata: {}
142
+ post_install_message:
143
+ rdoc_options: []
144
+ require_paths:
145
+ - lib
146
+ required_ruby_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ required_rubygems_version: !ruby/object:Gem::Requirement
152
+ requirements:
153
+ - - ">="
154
+ - !ruby/object:Gem::Version
155
+ version: '0'
156
+ requirements: []
157
+ rubygems_version: 3.0.3
158
+ signing_key:
159
+ specification_version: 4
160
+ summary: Verify ruby-graphql responses with a :graphql spec type
161
+ test_files: []