rspec-activerecord-formatter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 215510c55bb74fa62a54c9237eed2f99f795916c
4
+ data.tar.gz: 57949cc504f9e0f5dfefa1e6bb94482c95279b7f
5
+ SHA512:
6
+ metadata.gz: 5eae4c34002844511d9f683e2c22dc7135825ce36ed46c24f83239fe476551161940ce10dce02881e0f951d6952a189fb19d0ac8c586d5c443bc83452b2e7ffc
7
+ data.tar.gz: adac5f5c0819573703708c2ee6d34362ff0f127f9c0b67f2c16126901cee2dd84a4ccde4f208120963b1d0b0691722fc9dbc2643cb2b4dd3353a9bec8f6c9bd7
@@ -0,0 +1 @@
1
+ .DS_Store
@@ -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 jmmastey@gmail.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,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
@@ -0,0 +1,20 @@
1
+ Copyright 2016 Joseph Mastey
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,59 @@
1
+ RSpec Active Record Formatter
2
+ =============
3
+
4
+ Adds a new formatting option to rspec that counts your ActiveRecord queries
5
+ and object creations.
6
+
7
+ Why? Because database interaction is really slow, and careless creation of large
8
+ graphs of objects is a primary cause of insanely slow test suites. This project
9
+ can help you diagnose where you're doing the most damage so that you can
10
+ start to fix it.
11
+
12
+ This library plays nicely with DatabaseCleaner.
13
+
14
+ Installation
15
+ ------------
16
+
17
+ Normal bundle stuff.
18
+
19
+ gem rspec-activerecord-formatter
20
+
21
+
22
+ Usage
23
+ ------------
24
+
25
+ The current answer appears to be changing your `.rspec` initializer to include the following:
26
+
27
+ --require rails_helper
28
+ --format ActiveRecordFormatter
29
+
30
+ We have to include the rails_helper so that ActiveRecord is loaded prior to trying to load the
31
+ formatter. That way, we can hook into AR creations.
32
+
33
+ Once you set the formatter, you should now see the number of objects created and total queries
34
+ for each of your tests:
35
+
36
+ ![Tests with AR annotations.](https://github.com/jmmastey/rspec-activerecord-formatter/raw/master/doc/images/demo_2.png "Tests with AR annotations.")
37
+
38
+ You'll also get a summary at the end of your test run:
39
+
40
+ ![Test summary.](https://github.com/jmmastey/rspec-activerecord-formatter/raw/master/doc/images/demo_1.png "Test summary.")
41
+
42
+ Next Steps
43
+ ------------
44
+ * The method I was using to count AR objects doesn't work well with DatabaseCleaner when not explicitly wiring the library into `before` blocks.
45
+ I'd like to be able to go back to a method other than scanning for `INSERT INTO` strings.
46
+ * Configuration, especially of the aligning of the metric output (to outdent it optionally).
47
+ * Add a `--profile`-like behavior to output the most offending tests.
48
+
49
+ Contributing
50
+ ------------
51
+
52
+ Contributions are very welcome. Fork, fix, submit pulls.
53
+
54
+ Contribution is expected to conform to the [Contributor Covenant](https://github.com/jmmastey/rspec-activerecord-formatter/blob/master/CODE_OF_CONDUCT.md).
55
+
56
+ License
57
+ ------------
58
+
59
+ This software is released under the [MIT License](https://github.com/jmmastey/rspec-activerecord-formatter/blob/master/MIT-LICENSE).
Binary file
Binary file
@@ -0,0 +1,5 @@
1
+ require_relative "formatter/collector"
2
+ require_relative "formatter/formatter"
3
+
4
+ module ActiveRecordFormatter
5
+ end
@@ -0,0 +1,54 @@
1
+ require 'active_support/notifications'
2
+
3
+ module ActiveRecordFormatter
4
+ class Collector
5
+ attr_reader :query_count, :objects_count, :total_queries, :total_objects
6
+ SKIP_QUERIES = ["SELECT tablename FROM pg_tables", "select sum(ct) from (select count(*) ct from"]
7
+
8
+ def initialize
9
+ @query_count = 0
10
+ @objects_count = 0
11
+ @total_queries = 0
12
+ @total_objects = 0
13
+
14
+ ActiveSupport::Notifications.subscribe("sql.active_record", method(:record_query))
15
+ end
16
+
17
+ def record_query(*_unused, data)
18
+ return if SKIP_QUERIES.any? { |q| data[:sql].index(q) == 0 }
19
+
20
+ @query_count += 1
21
+ @total_queries += 1
22
+
23
+ if query_is_an_insert?(data[:sql])
24
+ @objects_count += 1
25
+ @total_objects += 1
26
+ end
27
+ end
28
+
29
+ def reset_example
30
+ @query_count = 0
31
+ @objects_count = 0
32
+ end
33
+
34
+ protected
35
+
36
+ # TODO: what happens if we try to create many records at once?
37
+ # TODO: are there any false positives we need to worry about? false negatives?
38
+ def query_is_an_insert?(query)
39
+ query =~ /INSERT INTO/
40
+ end
41
+ end
42
+ end
43
+
44
+ # This is actually a really nice way to count records, but sadly
45
+ # we have no way to hook a before action that preceeds DatabaseCleaner.
46
+ # That makes it awfully tough to count anything at all.
47
+ # def self.active_record_count
48
+ # tables = (ActiveRecord::Base.connection.tables - ["ar_internal_metadata", "schema_migrations"])
49
+ # rows = tables.map { |t| "select count(*) ct from #{t}" }.join(" union ")
50
+ # value = "select sum(ct) from (#{rows}) t"
51
+ #
52
+ # response = ActiveRecord::Base.connection.execute(value)
53
+ # response.to_a.first["sum"].to_i
54
+ # end
@@ -0,0 +1,71 @@
1
+ module ActiveRecordFormatter
2
+ class Formatter < ::RSpec::Core::Formatters::DocumentationFormatter
3
+ attr_reader :collector, :colorizer, :configuration
4
+
5
+ ::RSpec::Core::Formatters.register self, :start, :dump_summary,
6
+ :example_started, :example_passed, :example_failed
7
+
8
+ def initialize(output)
9
+ super
10
+
11
+ @colorizer = ::RSpec::Core::Formatters::ConsoleCodes
12
+ @collector = ActiveRecordFormatter::Collector.new
13
+ end
14
+
15
+ def start(start_notification)
16
+ output.puts "Recording and reporting ActiveRecord select and creation counts."
17
+ end
18
+
19
+ def example_started(example)
20
+ collector.reset_example
21
+ end
22
+
23
+ def dump_summary(summary)
24
+ formatted = "\nFinished in #{summary.formatted_duration} " \
25
+ "(files took #{summary.formatted_load_time} to load)\n" \
26
+ "#{colorized_expanded_totals(summary)}\n"
27
+
28
+ unless summary.failed_examples.empty?
29
+ formatted << summary.colorized_rerun_commands(colorizer) << "\n"
30
+ end
31
+
32
+ output.puts formatted
33
+ end
34
+
35
+ protected
36
+
37
+ def passed_output(example)
38
+ "#{current_indentation}#{example_counts}" +
39
+ colorizer.wrap(example.description.strip, :success)
40
+ end
41
+
42
+ def failure_output(example)
43
+ "#{current_indentation}#{example_counts}" +
44
+ colorizer.wrap("#{example.description.strip} (FAILED - #{next_failure_index})", :failure)
45
+ end
46
+
47
+ def example_counts(suffix: " ")
48
+ "(%02d, %02d)#{suffix}" % [collector.objects_count, collector.query_count]
49
+ end
50
+
51
+ def colorized_expanded_totals(summary)
52
+ if summary.failure_count > 0
53
+ colorizer.wrap(expanded_totals_line(summary), RSpec.configuration.failure_color)
54
+ elsif summary.pending_count > 0
55
+ colorizer.wrap(expanded_totals_line(summary), RSpec.configuration.pending_color)
56
+ else
57
+ colorizer.wrap(expanded_totals_line(summary), RSpec.configuration.success_color)
58
+ end
59
+ end
60
+
61
+ def expanded_totals_line(summary)
62
+ summary_text = ::RSpec::Core::Formatters::Helpers.pluralize(summary.example_count, "example")
63
+ summary_text << ", " << ::RSpec::Core::Formatters::Helpers.pluralize(summary.failure_count, "failure")
64
+ summary_text << ", #{summary.pending_count} pending" if summary.pending_count > 0
65
+ summary_text << ", #{collector.total_objects} AR objects"
66
+ summary_text << ", #{collector.total_queries} AR queries"
67
+
68
+ summary_text
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,3 @@
1
+ module ActiveRecordFormatter
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,34 @@
1
+ # encoding: utf-8
2
+
3
+ lib_dir = File.join(File.dirname(__FILE__),'lib')
4
+ $LOAD_PATH << lib_dir unless $LOAD_PATH.include?(lib_dir)
5
+
6
+ require 'rspec/activerecord/formatter/version'
7
+
8
+ Gem::Specification.new do |gem|
9
+
10
+ gem.name = "rspec-activerecord-formatter"
11
+ gem.version = ActiveRecordFormatter::VERSION
12
+
13
+ gem.summary = "Adds object creations and queries to Rspec output."
14
+ gem.description = "Creates a new formatter for ActiveRecord that can help you diagnose performance issues in RSpec"
15
+ gem.licenses = "MIT"
16
+ gem.authors = "Joseph Mastey"
17
+ gem.email = "jmmastey@gmail.com"
18
+ gem.homepage = "http://github.com/jmmastey/rspec-activerecord-formatter"
19
+
20
+ glob = lambda { |patterns| gem.files & Dir[*patterns] }
21
+
22
+ gem.files = `git ls-files`.split($/)
23
+
24
+ gem.extensions = glob['ext/**/extconf.rb']
25
+ gem.test_files = glob['{spec/{**/}*_spec.rb']
26
+ gem.extra_rdoc_files = glob['*.{txt,md}']
27
+
28
+ gem.require_paths = %w[ext lib].select { |dir| File.directory?(dir) }
29
+
30
+ # TODO: these are almost certainly too restrictive.
31
+ gem.add_dependency "bundler", "~> 1.9"
32
+ gem.add_dependency "activesupport", ">= 4.0"
33
+ gem.add_dependency "rspec", "~> 3.4"
34
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rspec-activerecord-formatter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Joseph Mastey
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-12-16 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.9'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.9'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '4.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '4.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ~>
46
+ - !ruby/object:Gem::Version
47
+ version: '3.4'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ~>
53
+ - !ruby/object:Gem::Version
54
+ version: '3.4'
55
+ description: Creates a new formatter for ActiveRecord that can help you diagnose performance
56
+ issues in RSpec
57
+ email: jmmastey@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files:
61
+ - CODE_OF_CONDUCT.md
62
+ - README.md
63
+ files:
64
+ - .gitignore
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - MIT-LICENSE
68
+ - README.md
69
+ - doc/images/demo_1.png
70
+ - doc/images/demo_2.png
71
+ - lib/rspec/activerecord/formatter.rb
72
+ - lib/rspec/activerecord/formatter/collector.rb
73
+ - lib/rspec/activerecord/formatter/formatter.rb
74
+ - lib/rspec/activerecord/formatter/version.rb
75
+ - rspec-activerecord-formatter.gemspec
76
+ homepage: http://github.com/jmmastey/rspec-activerecord-formatter
77
+ licenses:
78
+ - MIT
79
+ metadata: {}
80
+ post_install_message:
81
+ rdoc_options: []
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - '>='
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ required_rubygems_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - '>='
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ requirements: []
95
+ rubyforge_project:
96
+ rubygems_version: 2.0.14
97
+ signing_key:
98
+ specification_version: 4
99
+ summary: Adds object creations and queries to Rspec output.
100
+ test_files: []