rspec_sql_counter 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: b3ce43e54187e988093073b88a7002067d9d5bb8f10907343c1a0a641834ba5a
4
+ data.tar.gz: 66dd87f846462577bca035693de9ab5b6d9aba74a606bc96283b95b111365b80
5
+ SHA512:
6
+ metadata.gz: 91c793479c84529b789fb8f2eed06ed72aadec35cd3f8abef569661d96572c22ee46ec2b1233b29e52a554f5425216228097a28635b1cfbe17bb711f1de995da
7
+ data.tar.gz: 3bdc7359884eea6f5c78c8ce19174f18df7ce67199d9c2f70f36addfbc9f0094f9cebab4fa7bbc689d41aadeca57bc0f982454956e5848a3d0e5ea5798287afa
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,65 @@
1
+ AllCops:
2
+ NewCops: enable
3
+
4
+ require:
5
+ - rubocop-rspec
6
+ - rubocop-rails
7
+
8
+ Metrics/MethodLength:
9
+ Description: "Avoid methods longer than 50 lines of code."
10
+ Enabled: true
11
+ Max: 50
12
+
13
+ Metrics/ParameterLists:
14
+ Description: "Avoid parameter lists longer than three or four parameters."
15
+ Enabled: false
16
+
17
+ Style/Documentation:
18
+ Description: "Document classes and non-namespace modules."
19
+ Enabled: false
20
+
21
+ Metrics/AbcSize:
22
+ Description: >-
23
+ A calculated magnitude based on number of assignments,
24
+ branches, and conditions.
25
+ Enabled: false
26
+
27
+ Rails/Output:
28
+ Description: "Checks for calls to puts, print, etc."
29
+ Enabled: false
30
+
31
+ Metrics/ClassLength:
32
+ Description: "Avoid classes longer than 100 lines of code."
33
+ Enabled: false
34
+
35
+ Metrics/CyclomaticComplexity:
36
+ Description: >-
37
+ A complexity metric that is strongly correlated to the number
38
+ of test cases needed to validate a method.
39
+ Max: 20
40
+ Enabled: true
41
+
42
+ Metrics/PerceivedComplexity:
43
+ Description: A complexity metric geared towards measuring complexity for a human reader.
44
+ Enabled: true
45
+ Max: 20
46
+
47
+ Layout/LineLength:
48
+ Description: "Limit lines to 120 characters."
49
+ Max: 120
50
+ Exclude:
51
+ - 'spec/**/*'
52
+
53
+ RSpec/AnyInstance:
54
+ Enabled: false
55
+
56
+ RSpec/StubbedMock:
57
+ Enabled: false
58
+
59
+ RSpec/MultipleExpectations:
60
+ Description: Checks if examples contain too many `expect` calls.
61
+ Enabled: false
62
+
63
+ RSpec/ExampleLength:
64
+ Description: Checks for long examples.
65
+ Enabled: false
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at npatutina@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in rspec_sql_matcher.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 13.0'
9
+
10
+ gem 'rspec', '~> 3.0'
11
+
12
+ gem 'database_cleaner'
13
+ gem 'rubocop-rails', require: false
14
+ gem 'rubocop-rspec', require: false
data/Gemfile.lock ADDED
@@ -0,0 +1,218 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rspec_sql_counter (0.1.0)
5
+ rails (>= 4.0.13)
6
+ rspec (~> 3.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ actioncable (7.0.3)
12
+ actionpack (= 7.0.3)
13
+ activesupport (= 7.0.3)
14
+ nio4r (~> 2.0)
15
+ websocket-driver (>= 0.6.1)
16
+ actionmailbox (7.0.3)
17
+ actionpack (= 7.0.3)
18
+ activejob (= 7.0.3)
19
+ activerecord (= 7.0.3)
20
+ activestorage (= 7.0.3)
21
+ activesupport (= 7.0.3)
22
+ mail (>= 2.7.1)
23
+ net-imap
24
+ net-pop
25
+ net-smtp
26
+ actionmailer (7.0.3)
27
+ actionpack (= 7.0.3)
28
+ actionview (= 7.0.3)
29
+ activejob (= 7.0.3)
30
+ activesupport (= 7.0.3)
31
+ mail (~> 2.5, >= 2.5.4)
32
+ net-imap
33
+ net-pop
34
+ net-smtp
35
+ rails-dom-testing (~> 2.0)
36
+ actionpack (7.0.3)
37
+ actionview (= 7.0.3)
38
+ activesupport (= 7.0.3)
39
+ rack (~> 2.0, >= 2.2.0)
40
+ rack-test (>= 0.6.3)
41
+ rails-dom-testing (~> 2.0)
42
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
43
+ actiontext (7.0.3)
44
+ actionpack (= 7.0.3)
45
+ activerecord (= 7.0.3)
46
+ activestorage (= 7.0.3)
47
+ activesupport (= 7.0.3)
48
+ globalid (>= 0.6.0)
49
+ nokogiri (>= 1.8.5)
50
+ actionview (7.0.3)
51
+ activesupport (= 7.0.3)
52
+ builder (~> 3.1)
53
+ erubi (~> 1.4)
54
+ rails-dom-testing (~> 2.0)
55
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
56
+ activejob (7.0.3)
57
+ activesupport (= 7.0.3)
58
+ globalid (>= 0.3.6)
59
+ activemodel (7.0.3)
60
+ activesupport (= 7.0.3)
61
+ activerecord (7.0.3)
62
+ activemodel (= 7.0.3)
63
+ activesupport (= 7.0.3)
64
+ activestorage (7.0.3)
65
+ actionpack (= 7.0.3)
66
+ activejob (= 7.0.3)
67
+ activerecord (= 7.0.3)
68
+ activesupport (= 7.0.3)
69
+ marcel (~> 1.0)
70
+ mini_mime (>= 1.1.0)
71
+ activesupport (7.0.3)
72
+ concurrent-ruby (~> 1.0, >= 1.0.2)
73
+ i18n (>= 1.6, < 2)
74
+ minitest (>= 5.1)
75
+ tzinfo (~> 2.0)
76
+ ast (2.4.2)
77
+ builder (3.2.4)
78
+ concurrent-ruby (1.2.2)
79
+ crass (1.0.6)
80
+ database_cleaner (2.0.2)
81
+ database_cleaner-active_record (>= 2, < 3)
82
+ database_cleaner-active_record (2.1.0)
83
+ activerecord (>= 5.a)
84
+ database_cleaner-core (~> 2.0.0)
85
+ database_cleaner-core (2.0.1)
86
+ diff-lcs (1.5.0)
87
+ digest (3.1.0)
88
+ erubi (1.10.0)
89
+ globalid (1.0.0)
90
+ activesupport (>= 5.0)
91
+ i18n (1.12.0)
92
+ concurrent-ruby (~> 1.0)
93
+ json (2.6.3)
94
+ loofah (2.18.0)
95
+ crass (~> 1.0.2)
96
+ nokogiri (>= 1.5.9)
97
+ mail (2.7.1)
98
+ mini_mime (>= 0.1.1)
99
+ marcel (1.0.2)
100
+ method_source (1.0.0)
101
+ mini_mime (1.1.2)
102
+ minitest (5.18.0)
103
+ net-imap (0.2.3)
104
+ digest
105
+ net-protocol
106
+ strscan
107
+ net-pop (0.1.1)
108
+ digest
109
+ net-protocol
110
+ timeout
111
+ net-protocol (0.1.3)
112
+ timeout
113
+ net-smtp (0.3.1)
114
+ digest
115
+ net-protocol
116
+ timeout
117
+ nio4r (2.5.8)
118
+ nokogiri (1.13.6-x86_64-darwin)
119
+ racc (~> 1.4)
120
+ parallel (1.22.1)
121
+ parser (3.2.1.1)
122
+ ast (~> 2.4.1)
123
+ pg (1.4.6)
124
+ racc (1.6.0)
125
+ rack (2.2.3.1)
126
+ rack-test (1.1.0)
127
+ rack (>= 1.0, < 3)
128
+ rails (7.0.3)
129
+ actioncable (= 7.0.3)
130
+ actionmailbox (= 7.0.3)
131
+ actionmailer (= 7.0.3)
132
+ actionpack (= 7.0.3)
133
+ actiontext (= 7.0.3)
134
+ actionview (= 7.0.3)
135
+ activejob (= 7.0.3)
136
+ activemodel (= 7.0.3)
137
+ activerecord (= 7.0.3)
138
+ activestorage (= 7.0.3)
139
+ activesupport (= 7.0.3)
140
+ bundler (>= 1.15.0)
141
+ railties (= 7.0.3)
142
+ rails-dom-testing (2.0.3)
143
+ activesupport (>= 4.2.0)
144
+ nokogiri (>= 1.6)
145
+ rails-html-sanitizer (1.4.3)
146
+ loofah (~> 2.3)
147
+ railties (7.0.3)
148
+ actionpack (= 7.0.3)
149
+ activesupport (= 7.0.3)
150
+ method_source
151
+ rake (>= 12.2)
152
+ thor (~> 1.0)
153
+ zeitwerk (~> 2.5)
154
+ rainbow (3.1.1)
155
+ rake (13.0.6)
156
+ regexp_parser (2.7.0)
157
+ rexml (3.2.5)
158
+ rspec (3.12.0)
159
+ rspec-core (~> 3.12.0)
160
+ rspec-expectations (~> 3.12.0)
161
+ rspec-mocks (~> 3.12.0)
162
+ rspec-core (3.12.1)
163
+ rspec-support (~> 3.12.0)
164
+ rspec-expectations (3.12.2)
165
+ diff-lcs (>= 1.2.0, < 2.0)
166
+ rspec-support (~> 3.12.0)
167
+ rspec-mocks (3.12.4)
168
+ diff-lcs (>= 1.2.0, < 2.0)
169
+ rspec-support (~> 3.12.0)
170
+ rspec-support (3.12.0)
171
+ rubocop (1.48.1)
172
+ json (~> 2.3)
173
+ parallel (~> 1.10)
174
+ parser (>= 3.2.0.0)
175
+ rainbow (>= 2.2.2, < 4.0)
176
+ regexp_parser (>= 1.8, < 3.0)
177
+ rexml (>= 3.2.5, < 4.0)
178
+ rubocop-ast (>= 1.26.0, < 2.0)
179
+ ruby-progressbar (~> 1.7)
180
+ unicode-display_width (>= 2.4.0, < 3.0)
181
+ rubocop-ast (1.27.0)
182
+ parser (>= 3.2.1.0)
183
+ rubocop-capybara (2.17.1)
184
+ rubocop (~> 1.41)
185
+ rubocop-rails (2.18.0)
186
+ activesupport (>= 4.2.0)
187
+ rack (>= 1.1)
188
+ rubocop (>= 1.33.0, < 2.0)
189
+ rubocop-rspec (2.19.0)
190
+ rubocop (~> 1.33)
191
+ rubocop-capybara (~> 2.17)
192
+ ruby-progressbar (1.13.0)
193
+ strscan (3.0.3)
194
+ thor (1.2.1)
195
+ timeout (0.3.0)
196
+ tzinfo (2.0.6)
197
+ concurrent-ruby (~> 1.0)
198
+ unicode-display_width (2.4.2)
199
+ websocket-driver (0.7.5)
200
+ websocket-extensions (>= 0.1.0)
201
+ websocket-extensions (0.1.5)
202
+ zeitwerk (2.6.0)
203
+
204
+ PLATFORMS
205
+ x86_64-darwin-21
206
+
207
+ DEPENDENCIES
208
+ bundler (~> 2.0)
209
+ database_cleaner
210
+ pg (~> 1.4)
211
+ rake (~> 13.0)
212
+ rspec (~> 3.0)
213
+ rspec_sql_counter!
214
+ rubocop-rails
215
+ rubocop-rspec
216
+
217
+ BUNDLED WITH
218
+ 2.4.8
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 nastyapatutina
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,65 @@
1
+ # RSpec SQL Matcher
2
+
3
+ Welcome to rspec_sql_matcher gem!
4
+
5
+ It helps you to test SQL queries, that are called in code blocks.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'rspec_sql_matcher'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ gem install rspec_sql_matcher
22
+
23
+ ## Usage
24
+
25
+ To test that query called in method, add this code on your it-block:
26
+
27
+ expect { ReportGenerator.call }.to call_sql_query('SELECT COUNT(*) FROM "users"')
28
+
29
+ Also to test query not called in method use:
30
+
31
+ expect { ReportGenerator.call }.not_to call_sql_query('SELECT COUNT(*) FROM "users"')
32
+
33
+ You can restrict the matcher using times counter:
34
+
35
+ expect { ReportGenerator.call }.to call_sql_query('SELECT COUNT(*) FROM "users"').times(2)
36
+
37
+ You can restrict the matcher using bind values:
38
+
39
+ expect { ReportGenerator.call }.to call_sql_query('SELECT "users".* FROM "users" WHERE "users"."name" = $1').with('Karl')
40
+
41
+ Below is an example of a description of an error in tests
42
+
43
+ ```
44
+ Expected to call SQL query SELECT "companies".* FROM "companies" LIMIT $1 OFFSET $2 with values [1, 2] 1 times, but found this queries:
45
+ 3 times: SELECT COUNT(*) FROM "companies"
46
+ 1 times: SELECT COUNT(*) FROM (SELECT 1 AS one FROM "companies" LIMIT $1 OFFSET $2) subquery_for_count with values [5, 10]
47
+ ```
48
+
49
+ ## Development
50
+
51
+ 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.
52
+
53
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
54
+
55
+ ## Contributing
56
+
57
+ Bug reports and pull requests are welcome on GitHub at https://github.com/NastyaPatutina/rspec_sql_matcher. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/NastyaPatutina/rspec_sql_matcher/blob/main/CODE_OF_CONDUCT.md).
58
+
59
+ ## License
60
+
61
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
62
+
63
+ ## Code of Conduct
64
+
65
+ Everyone interacting in the RspecSqlMatcher project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/NastyaPatutina/rspec_sql_matcher/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'sql_fetcher'
4
+
5
+ module RspecSqlMatcher
6
+ module Matcher
7
+ # rubocop:disable Metrics/BlockLength
8
+ # Matcher for SQL queries
9
+ # Checks if the request was called, with what parameters and how many times
10
+ #
11
+ # @example
12
+ # expect{ subject }.not_to call_sql_query('SELECT "companies".* FROM "companies" LIMIT $1 OFFSET $2')
13
+ # expect{ subject }.to call_sql_query('SELECT COUNT(*) FROM "companies"').times(1)
14
+ RSpec::Matchers.define :call_sql_query do |expected|
15
+ supports_block_expectations
16
+
17
+ chain :with do |*bind_values|
18
+ @bind_values = *bind_values
19
+ end
20
+
21
+ chain :times do |count|
22
+ raise ArgumentError, "Incorrect times #{count.inspect}" unless count.is_a?(Integer) && !count.negative?
23
+
24
+ @count = count
25
+ end
26
+
27
+ chain :once do
28
+ @count = 1
29
+ end
30
+
31
+ match do |block|
32
+ find_queries(block)
33
+ @count ? @res_times == @count : @res_times.positive?
34
+ end
35
+
36
+ match_when_negated do |block|
37
+ find_queries(block)
38
+ @count ? @res_times != @count : @res_times.zero?
39
+ end
40
+
41
+ # Error text if no such requests are found
42
+ #
43
+ # @example
44
+ # Expected to call SQL query SELECT "companies".* FROM "companies" LIMIT $1 OFFSET $2 with values [1, 2]
45
+ # 1 times, but found this queries:
46
+ # 3 times: SELECT COUNT(*) FROM "companies"
47
+ # 1 times: SELECT COUNT(*) FROM (SELECT 1 AS one FROM "companies" LIMIT $1 OFFSET $2) subquery_for_count with
48
+ # values [5, 10]
49
+ # 1 times: SELECT "companies".* FROM "companies" LIMIT $1 OFFSET $2 with values [5, 10]
50
+ failure_message do |_|
51
+ prelude = "Expected to call SQL query #{expected}"
52
+ prelude += " with values #{@bind_values}" if @bind_values.present?
53
+
54
+ prelude += " #{@count} times" if @count.present?
55
+
56
+ "#{prelude}, but found this queries:\n#{pretty_queries(@all_queries)}"
57
+ end
58
+
59
+ # Error text if such requests are found
60
+ #
61
+ # @example
62
+ # Expected not to call SQL query SELECT "companies".* FROM "companies" LIMIT $1 OFFSET $2 1 times, but found
63
+ # this query:
64
+ # 1 times: SELECT "companies".* FROM "companies" LIMIT $1 OFFSET $2 with values [5, 10]
65
+ failure_message_when_negated do |_|
66
+ prelude = "Expected not to call SQL query #{expected}"
67
+ prelude += " with values #{@bind_values}" if @bind_values.present?
68
+
69
+ prelude += " #{@count} times" if @count.present?
70
+
71
+ "#{prelude}, but found this query:\n#{pretty_queries(@exp_queries)}"
72
+ end
73
+
74
+ private
75
+
76
+ # Pretty SqlHelper::SqlQueryInfo
77
+ def pretty_queries(queries)
78
+ queries.map(&:pretty_to_s).join("\n")
79
+ end
80
+
81
+ # Finds whether there was an SQL query with such a body and parameters
82
+ # Also counts how many times it was called
83
+ def find_queries(block)
84
+ # Finding all sql queries
85
+ @all_queries ||= SqlFetcher.sql_queries(block)
86
+
87
+ # Find queries with such sql body
88
+ @exp_queries = @all_queries.select { |q| q.sql == expected }
89
+
90
+ # We find requests with such bind values
91
+ @exp_queries = @exp_queries.select { |q| q.type_casted_binds == @bind_values } if @bind_values
92
+
93
+ # Count the number of times
94
+ @res_times = @exp_queries.sum(&:times)
95
+ end
96
+ end
97
+ # rubocop:enable Metrics/BlockLength
98
+ end
99
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RspecSqlMatcher
4
+ class SqlFetcher
5
+ SqlQueryInfo = Struct.new(:sql, :type_casted_binds, :times) do
6
+ # Pretty SqlHelper::SqlQueryInfo
7
+ #
8
+ # @return [String] Pretty text
9
+ def pretty_to_s
10
+ if type_casted_binds.present?
11
+ "#{times} times: #{sql} with values #{type_casted_binds}"
12
+ else
13
+ "#{times} times: #{sql}"
14
+ end
15
+ end
16
+ end
17
+
18
+ class << self
19
+ attr_reader :queries
20
+
21
+ # Collects all sql queries called in the specified block of code
22
+ #
23
+ # @return [Array<SqlQueryInfo>] list of collected sql queries and from quantity
24
+ # @example
25
+ # [
26
+ # #<struct SqlHelper::SqlQueryInfo sql="SELECT COUNT(*) FROM \"companies\"", type_casted_binds=[], times=1>,
27
+ # #<struct SqlHelper::SqlQueryInfo sql="SELECT \"companies\".* FROM \"companies\" LIMIT $1 OFFSET $2",
28
+ # type_casted_binds=[10, 10], times=1>
29
+ # ]
30
+ def sql_queries(block)
31
+ @queries = []
32
+
33
+ ActiveSupport::Notifications.subscribed(method(:active_support_callback), 'sql.active_record') do
34
+ block.call
35
+ end
36
+
37
+ queries
38
+ end
39
+
40
+ private
41
+
42
+ # Callback for ActiveSupport::Notifications - fill list @queries
43
+ def active_support_callback(_name, _started, _finished, _unique_id, payload)
44
+ return if %w[CACHE SCHEMA].include?(payload[:name])
45
+
46
+ old_query = exists_query(**payload.slice(:sql, :type_casted_binds))
47
+ # Если такой запрос уже был, просто увеличиваем его кол-во
48
+ if old_query.present?
49
+ old_query.times = old_query.times + 1
50
+ else
51
+ # Если не было - добавлем в общий список
52
+ queries << SqlQueryInfo.new(payload[:sql], payload[:type_casted_binds], 1)
53
+ end
54
+ end
55
+
56
+ # Finds whether there has already been such a SQL query and returns it
57
+ #
58
+ # @param sql [String] checked sql-query
59
+ # @param type_casted_binds [Array] checked binds
60
+ # @return [SqlQueryInfo, nil] found query
61
+ # If not found is nil
62
+ def exists_query(sql:, type_casted_binds:)
63
+ queries.find { |q| q.sql == sql && q.type_casted_binds == type_casted_binds }
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RspecSqlMatcher
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'rspec_sql_matcher/version'
4
+ require_relative 'rspec_sql_matcher/matcher'
5
+
6
+ module RspecSqlMatcher
7
+ class Error < StandardError; end
8
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/rspec_sql_matcher/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'rspec_sql_counter'
7
+ spec.version = RspecSqlMatcher::VERSION
8
+ spec.authors = ['Nastya Patutina']
9
+ spec.email = ['npatutina@gmail.com']
10
+
11
+ spec.summary = 'RSpec matcher for SQL queries'
12
+ spec.description = 'RSpec matcher for SQL queries'
13
+ spec.homepage = 'https://github.com/NastyaPatutina/rspec_sql_matcher'
14
+ spec.required_ruby_version = '>= 2.6.0'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = 'https://github.com/NastyaPatutina/rspec_sql_matcher'
18
+ spec.metadata['changelog_uri'] = 'https://github.com/NastyaPatutina/rspec_sql_matcher'
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(__dir__) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
25
+ end
26
+ end
27
+ spec.bindir = 'exe'
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ['lib']
30
+
31
+ spec.add_development_dependency 'bundler', '~> 2.0'
32
+ spec.add_development_dependency 'pg', '~> 1.4'
33
+ spec.add_development_dependency 'rake', '~> 10.0'
34
+
35
+ spec.add_runtime_dependency 'rails', '>= 4.0.13'
36
+ spec.add_runtime_dependency 'rspec', '~> 3.0'
37
+ spec.metadata['rubygems_mfa_required'] = 'true'
38
+ end
@@ -0,0 +1,4 @@
1
+ module RspecSqlMatcher
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,130 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rspec_sql_counter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nastya Patutina
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-05-01 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: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pg
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.4'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.4'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rails
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 4.0.13
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 4.0.13
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ description: RSpec matcher for SQL queries
84
+ email:
85
+ - npatutina@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".rspec"
91
+ - ".rubocop.yml"
92
+ - CODE_OF_CONDUCT.md
93
+ - Gemfile
94
+ - Gemfile.lock
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - lib/rspec_sql_matcher.rb
99
+ - lib/rspec_sql_matcher/matcher.rb
100
+ - lib/rspec_sql_matcher/sql_fetcher.rb
101
+ - lib/rspec_sql_matcher/version.rb
102
+ - rspec_sql_matcher.gemspec
103
+ - sig/rspec_sql_matcher.rbs
104
+ homepage: https://github.com/NastyaPatutina/rspec_sql_matcher
105
+ licenses: []
106
+ metadata:
107
+ homepage_uri: https://github.com/NastyaPatutina/rspec_sql_matcher
108
+ source_code_uri: https://github.com/NastyaPatutina/rspec_sql_matcher
109
+ changelog_uri: https://github.com/NastyaPatutina/rspec_sql_matcher
110
+ rubygems_mfa_required: 'true'
111
+ post_install_message:
112
+ rdoc_options: []
113
+ require_paths:
114
+ - lib
115
+ required_ruby_version: !ruby/object:Gem::Requirement
116
+ requirements:
117
+ - - ">="
118
+ - !ruby/object:Gem::Version
119
+ version: 2.6.0
120
+ required_rubygems_version: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ requirements: []
126
+ rubygems_version: 3.3.3
127
+ signing_key:
128
+ specification_version: 4
129
+ summary: RSpec matcher for SQL queries
130
+ test_files: []