From 392ef48121d91367ab61607fe355a342940cb5ca Mon Sep 17 00:00:00 2001 From: Thomas Sawyer Date: Sat, 21 Nov 2026 23:16:15 -0500 Subject: [PATCH 1/2] Modernize, and tell skipped examples from pending ones The formatter is rewritten on the same lines as Minitap's reporter. Skipped examples are reported as omit and pending ones as todo, both with their reason; a pending example that passes is a failure; what RSpec says outside of an example becomes a note. Packaging is a plain gemspec with GitHub Actions, testing Ruby 2.7 to 4.0 and the oldest RSpec 3. Co-Authored-By: Claude Fable 5.2 --- .gemspec | 307 ------------------ .github/workflows/ci.yml | 41 +++ .gitignore | 15 +- .index | 56 ---- .travis.yml | 13 - .yardopts | 5 +- Assembly | 25 -- Gemfile | 4 + HISTORY.md | 35 ++ INDEX.yml | 43 --- MANIFEST | 9 - README.md | 79 +++-- Rakefile | 22 ++ demo/01_tapy.md | 104 ++++++ demo/02_tapj.md | 35 ++ demo/03_pending.md | 57 ++++ demo/04_details.md | 115 +++++++ demo/05_tapout.md | 45 +++ demo/applique/ae.rb | 1 + demo/applique/run.rb | 49 +++ lib/rspec/ontap.rb | 632 ++++++++++++++----------------------- lib/rspec/ontap/version.rb | 5 + lib/rspec/tap_j.rb | 7 +- lib/rspec/tap_y.rb | 7 +- rspec-ontap.gemspec | 39 +++ try/spec_example.rb | 20 -- 26 files changed, 842 insertions(+), 928 deletions(-) delete mode 100644 .gemspec create mode 100644 .github/workflows/ci.yml delete mode 100644 .index delete mode 100644 .travis.yml delete mode 100644 Assembly delete mode 100644 INDEX.yml delete mode 100644 MANIFEST create mode 100644 Rakefile create mode 100644 demo/01_tapy.md create mode 100644 demo/02_tapj.md create mode 100644 demo/03_pending.md create mode 100644 demo/04_details.md create mode 100644 demo/05_tapout.md create mode 100644 demo/applique/ae.rb create mode 100644 demo/applique/run.rb create mode 100644 lib/rspec/ontap/version.rb create mode 100644 rspec-ontap.gemspec delete mode 100644 try/spec_example.rb diff --git a/.gemspec b/.gemspec deleted file mode 100644 index ea0db60..0000000 --- a/.gemspec +++ /dev/null @@ -1,307 +0,0 @@ -# encoding: utf-8 - -require 'yaml' -require 'pathname' - -module Indexer - - # Convert index data into a gemspec. - # - # Notes: - # * Assumes all executables are in bin/. - # * Does not yet handle default_executable setting. - # * Does not yet handle platform setting. - # * Does not yet handle required_ruby_version. - # * Support for rdoc entries is weak. - # - class GemspecExporter - - # File globs to include in package --unless a manifest file exists. - FILES = ".index .yardopts alt bin data demo ext features lib man spec test try* [A-Z]*.*" unless defined?(FILES) - - # File globs to omit from FILES. - OMIT = "Config.rb" unless defined?(OMIT) - - # Standard file patterns. - PATTERNS = { - :root => '{.index,Gemfile}', - :bin => 'bin/*', - :lib => 'lib/{**/}*', #.rb', - :ext => 'ext/{**/}extconf.rb', - :doc => '*.{txt,rdoc,md,markdown,tt,textile}', - :test => '{test,spec}/{**/}*.rb' - } unless defined?(PATTERNS) - - # For which revision of indexer spec is this converter intended? - REVISION = 2013 unless defined?(REVISION) - - # - def self.gemspec - new.to_gemspec - end - - # - attr :metadata - - # - def initialize(metadata=nil) - @root_check = false - - if metadata - root_dir = metadata.delete(:root) - if root_dir - @root = root_dir - @root_check = true - end - metadata = nil if metadata.empty? - end - - @metadata = metadata || YAML.load_file(root + '.index') - - if @metadata['revision'].to_i != REVISION - warn "This gemspec exporter was not designed for this revision of index metadata." - end - end - - # - def has_root? - root ? true : false - end - - # - def root - return @root if @root || @root_check - @root_check = true - @root = find_root - end - - # - def manifest - return nil unless root - @manifest ||= Dir.glob(root + 'manifest{,.txt}', File::FNM_CASEFOLD).first - end - - # - def scm - return nil unless root - @scm ||= %w{git hg}.find{ |m| (root + ".#{m}").directory? }.to_sym - end - - # - def files - return [] unless root - @files ||= \ - if manifest - File.readlines(manifest). - map{ |line| line.strip }. - reject{ |line| line.empty? || line[0,1] == '#' } - else - list = [] - Dir.chdir(root) do - FILES.split(/\s+/).each do |pattern| - list.concat(glob(pattern)) - end - OMIT.split(/\s+/).each do |pattern| - list = list - glob(pattern) - end - end - list - end.select{ |path| File.file?(path) }.uniq - end - - # - def glob_files(pattern) - return [] unless root - Dir.chdir(root) do - Dir.glob(pattern).select do |path| - File.file?(path) && files.include?(path) - end - end - end - - def patterns - PATTERNS - end - - def executables - @executables ||= \ - glob_files(patterns[:bin]).map do |path| - File.basename(path) - end - end - - def extensions - @extensions ||= \ - glob_files(patterns[:ext]).map do |path| - File.basename(path) - end - end - - def name - metadata['name'] || metadata['title'].downcase.gsub(/\W+/,'_') - end - - def homepage - page = ( - metadata['resources'].find{ |r| r['type'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^web/i } - ) - page ? page['uri'] : false - end - - def licenses - metadata['copyrights'].map{ |c| c['license'] }.compact - end - - def require_paths - paths = metadata['paths'] || {} - paths['load'] || ['lib'] - end - - # - # Convert to gemnspec. - # - def to_gemspec - if has_root? - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - else - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - end - end - - # - # Convert pure data settings. - # - def to_gemspec_data(gemspec) - gemspec.name = name - gemspec.version = metadata['version'] - gemspec.summary = metadata['summary'] - gemspec.description = metadata['description'] - - metadata['authors'].each do |author| - gemspec.authors << author['name'] - - if author.has_key?('email') - if gemspec.email - gemspec.email << author['email'] - else - gemspec.email = [author['email']] - end - end - end - - gemspec.licenses = licenses - - requirements = metadata['requirements'] || [] - requirements.each do |req| - next if req['optional'] - next if req['external'] - - name = req['name'] - groups = req['groups'] || [] - - version = gemify_version(req['version']) - - if groups.empty? or groups.include?('runtime') - # populate runtime dependencies - if gemspec.respond_to?(:add_runtime_dependency) - gemspec.add_runtime_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - else - # populate development dependencies - if gemspec.respond_to?(:add_development_dependency) - gemspec.add_development_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - end - end - - # convert external dependencies into gemspec requirements - requirements.each do |req| - next unless req['external'] - gemspec.requirements << ("%s-%s" % req.values_at('name', 'version')) - end - - gemspec.homepage = homepage - gemspec.require_paths = require_paths - gemspec.post_install_message = metadata['install_message'] - end - - # - # Set gemspec settings that require a root directory path. - # - def to_gemspec_paths(gemspec) - gemspec.files = files - gemspec.extensions = extensions - gemspec.executables = executables - - if Gem::VERSION < '1.7.' - gemspec.default_executable = gemspec.executables.first - end - - gemspec.test_files = glob_files(patterns[:test]) - - unless gemspec.files.include?('.document') - gemspec.extra_rdoc_files = glob_files(patterns[:doc]) - end - end - - # - # Return a copy of this file. This is used to generate a local - # .gemspec file that can automatically read the index file. - # - def self.source_code - File.read(__FILE__) - end - - private - - def find_root - root_files = patterns[:root] - if Dir.glob(root_files).first - Pathname.new(Dir.pwd) - elsif Dir.glob("../#{root_files}").first - Pathname.new(Dir.pwd).parent - else - #raise "Can't find root of project containing `#{root_files}'." - warn "Can't find root of project containing `#{root_files}'." - nil - end - end - - def glob(pattern) - if File.directory?(pattern) - Dir.glob(File.join(pattern, '**', '*')) - else - Dir.glob(pattern) - end - end - - def gemify_version(version) - case version - when /^(.*?)\+$/ - ">= #{$1}" - when /^(.*?)\-$/ - "< #{$1}" - when /^(.*?)\~$/ - "~> #{$1}" - else - version - end - end - - end - -end - -Indexer::GemspecExporter.gemspec \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d5d5b7f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + # Monthly, to catch breakage from new Ruby or RSpec releases + # when nothing has been pushed. + schedule: + - cron: '0 6 1 * *' + +permissions: + contents: read + +jobs: + test: + name: Ruby ${{ matrix.ruby }}, RSpec ${{ matrix.rspec || 'latest' }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { ruby: '2.7' } + - { ruby: '3.0' } + - { ruby: '3.1' } + - { ruby: '3.2' } + - { ruby: '3.3' } + - { ruby: '3.4' } + - { ruby: '4.0' } + # The oldest RSpec supported. + - { ruby: '2.7', rspec: '~> 3.0.0' } + env: + RSPEC_VERSION: ${{ matrix.rspec }} + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Demos + run: bundle exec qed -Ilib demo/ diff --git a/.gitignore b/.gitignore index 2e48ffc..d75bbdf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,7 @@ -.reap/digest +*.gem +*.lock .yardoc -doc -log -pkg -tmp -man/man1/index.txt -man/man1/*.html -man/man1/*.1 -web +doc/ +log/ +pkg/ +tmp/ diff --git a/.index b/.index deleted file mode 100644 index 840e063..0000000 --- a/.index +++ /dev/null @@ -1,56 +0,0 @@ ---- -revision: 2013 -type: ruby -sources: -- INDEX.yml -authors: -- name: Trans - email: transfire@gmail.com -organizations: -- name: Rubyworks -requirements: -- name: rspec -- name: tapout -- groups: - - build - development: true - name: mast -- groups: - - build - development: true - name: indexer -conflicts: [] -alternatives: [] -resources: -- type: home - uri: http://rubyworks.github.com/rspec-ontap - label: Homepage -- type: code - uri: http://github.com/rubyworks/rspec-ontap - label: Source Code -- type: bugs - uri: http://github.com/rubyworks/rspec-ontap/issues - label: Issue Tracker -- type: chat - uri: irc://chat.us.freenode.net#rubyworks - label: IRC Channel -repositories: -- name: upstream - scm: git - uri: git://github.com/rubyworks/rspec-ontap.git -categories: [] -copyrights: -- holder: Rubyworks - year: '2011' - license: BSD-2-Clause -customs: [] -paths: - lib: - - lib -name: rspec-ontap -title: RSpec-On-Tap -version: 0.3.0 -summary: RSpec On Tap-Y/J -description: RSpec-On-Tap is a TAP-Y/J formatter for RSpec. -created: '2011-12-13' -date: '2015-01-17' diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 83b4fdf..0000000 --- a/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ ---- -language: ruby -script: "bundle exec qed" -rvm: - - 2.1.0 - - 2.0.0 - - 1.9.3 - - rbx - - jruby -matrix: - allow_failures: - - rvm: rbx -cache: bundler diff --git a/.yardopts b/.yardopts index cad9e38..8352b71 100644 --- a/.yardopts +++ b/.yardopts @@ -1,9 +1,8 @@ ---title VCLog +--title "RSpec On Tap" +--readme README.md --protected --private lib/ - *.md *.txt -*.yml - diff --git a/Assembly b/Assembly deleted file mode 100644 index f13aa84..0000000 --- a/Assembly +++ /dev/null @@ -1,25 +0,0 @@ ---- -email: - mailto: - - ruby-talk@ruby-lang.org - - rubyworks-mailinglist@googlegroups.com - -gem: - active: true - -github: - folder: web - -dnote: - title: Source Notes - output: log/notes.html - files: lib/**/*.rb - -locat: - output: log/locat.html - -vclog: - output: - - log/history.html - - log/changes.html - diff --git a/Gemfile b/Gemfile index 3be9c3c..47031f4 100644 --- a/Gemfile +++ b/Gemfile @@ -1,2 +1,6 @@ source "https://rubygems.org" gemspec + +# To test against a particular RSpec, e.g. RSPEC_VERSION='~> 3.0.0'. +version = ENV['RSPEC_VERSION'].to_s +gem 'rspec', version unless version.empty? diff --git a/HISTORY.md b/HISTORY.md index 9e04e78..ef0f23d 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,40 @@ # Release History +## Unreleased + +RSpec On Tap runs on current Ruby and RSpec, and tells skipped examples +from pending ones. It needs Ruby 2.7 or newer and RSpec 3. + +Changes: + +* Report an example that was skipped (`skip`, `xit`) with the status + `omit`. One that is pending, or has no body yet, is still a `todo`. + All four were `todo` before. +* Give the reason an example was skipped or is pending, as the message + of the record's exception section. +* Report a pending example that passes as a failure, as RSpec does. It + was reported as an error. +* Report a failed mock expectation as a failure, too. +* Pass on what RSpec says outside of an example, such as an error while + loading a spec file, as a note. It was dropped. +* Leave out the seed when the examples don't run in random order. +* No longer raise when a failure's backtrace is empty or names a file + that can't be read. +* Require Tapout 0.5 or newer. +* `RSpec::OnTap::VERSION` gives the version. +* Replace the old packaging (`.index`, `.gemspec`, `Assembly`, + `MANIFEST`) with a plain `rspec-ontap.gemspec`, and Travis with GitHub + Actions, testing Ruby 2.7 to 4.0. + + +## 0.3.1 / 2015-07-17 + +Changes: + +* Fix calls to `relative_path`, which raised NoMethodError for every + passing and pending example (#2). + + ## 0.3.0 / 2014-01-17 This is a major overhaul of the formatter to work with RSpec 3+. diff --git a/INDEX.yml b/INDEX.yml deleted file mode 100644 index e0744cb..0000000 --- a/INDEX.yml +++ /dev/null @@ -1,43 +0,0 @@ ---- -name: - rspec-ontap - -version: - 0.3.0 - -title: - RSpec-On-Tap - -summary: - RSpec On Tap-Y/J - -description: - RSpec-On-Tap is a TAP-Y/J formatter for RSpec. - -requirements: -- rspec -- tapout -- mast (build) -- indexer (build) -#- detroit (build) - -resources: - home: http://rubyworks.github.com/rspec-ontap - code: http://github.com/rubyworks/rspec-ontap - bugs: http://github.com/rubyworks/rspec-ontap/issues - chat: irc://chat.us.freenode.net#rubyworks - -repositories: - upstream: git://github.com/rubyworks/rspec-ontap.git - -authors: -- Trans - -organizations: -- Rubyworks - -copyrights: -- (c) 2011 Rubyworks (BSD-2-Clause) - -created: - 2011-12-13 diff --git a/MANIFEST b/MANIFEST deleted file mode 100644 index 83f2ce8..0000000 --- a/MANIFEST +++ /dev/null @@ -1,9 +0,0 @@ -#!mast .index .yardopts bin features lib man spec test *.md *.txt -.index -.yardopts -lib/rspec/ontap.rb -lib/rspec/tap_j.rb -lib/rspec/tap_y.rb -README.md -HISTORY.md -LICENSE.txt diff --git a/README.md b/README.md index fd4d070..cf24c8b 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,79 @@ # RSpec On Tap -[Homepage](http://rubyworks.github.com/rspec-ontap) | -[Source Code](http://github.com/rubyworks/rspec-ontap) | -[Report Issue](http://github.com/rubyworks/rspec-ontap/issues) +[Documentation](https://rubydoc.info/gems/rspec-ontap) | +[Report Issue](https://github.com/rubyworks/rspec-ontap/issues) | +[Source Code](https://github.com/rubyworks/rspec-ontap) +[![CI](https://github.com/rubyworks/rspec-ontap/actions/workflows/ci.yml/badge.svg)](https://github.com/rubyworks/rspec-ontap/actions/workflows/ci.yml) +[![Gem Version](https://badge.fury.io/rb/rspec-ontap.svg)](https://badge.fury.io/rb/rspec-ontap) -## Description - -**RSpec On Tap** is a TAP-Y/J formatter for RSpec. -The latest version works with **RSpec 3+ only**. +## Description -You can learn more about TAP-Y/J [here](https://github.com/rubyworks/tapout). +**RSpec On Tap** is a pair of formatters for [RSpec](https://rspec.info) +that report in TAP-Y or TAP-J. Those are the formats that +[Tapout](https://github.com/rubyworks/tapout) reads, so with RSpec On Tap +a suite of specs can be shown in any of Tapout's report formats. + $ rspec -f RSpec::TapY | tapout progress -## Usage +It works with RSpec 3, on Ruby 2.7 and newer. -Usage is simply a matter of requiring the plugin and passing the name of the -format class to the `rspec` command via the `-f` option. - $ rspec -r rspec/ontap -f RSpec::TapY spec/*.rb +## Installation -This can be shortened to just: + $ gem install rspec-ontap - $ rspec -f RSpec::TapY spec/*.rb +Or in a Gemfile: -This works because RSpec will automatically require a related path -- in this -case `rspec/tap_y` -- if the class if initially undefined. The library file -`rspec/tap_y` itself simply requires `rspec/ontap` (the same is true for -`rspec/tap_j`). + group :test do + gem "rspec-ontap", :require => false + end -With TAP-Y output in hand, the `tapout` tool can then be used to produce a -variety of other output formats. First, make sure Tapout is installed: +Tapout is installed along with it. - $ gem install tapout -Then, for example: +## Usage - $ rspec -f RSpec::TapY spec/*.rb | tapout progress +Give the `rspec` command the name of the formatter with its `-f` option: +`RSpec::TapY` for TAP-Y, or `RSpec::TapJ` for TAP-J. -See the [TapOut project](http://rubyworks.github.com/tapout) for more information. + $ rspec -f RSpec::TapY +Nothing has to be required. When RSpec doesn't know a formatter, it +requires a file named after it, here `rspec/tap_y`, and that loads the +formatters. If you'd rather be explicit: + $ rspec -r rspec/ontap -f RSpec::TapY -## Installation +The output is a TAP-Y stream, which isn't meant to be read as it is. +Pipe it to `tapout`, with the name of the report you want: -Installation follows the usual pattern: + $ rspec -f RSpec::TapY | tapout progress - $ gem install rspec-ontap +`tapout --help` lists the reports. -Or using your Gemfile, add something like: +### What is reported - group :test do - gem "rspec-ontap", :require => false - end +* Each example group is a case, nested as the groups are, and each + example a test. +* A failure or error comes with its message, the file and line, the + lines of source around it, and RSpec's backtrace. An expectation that + wasn't met is a failure; anything else raised is an error. +* An example that was skipped, with `skip` or `xit`, is reported as + omitted. One that is pending, or has no body yet, is reported as still + to be done. Both give the reason. +* What an example prints to `$stdout` and `$stderr` is captured and + reported with the example, since it would otherwise break the stream. +* Anything RSpec says outside of an example, such as an error while + loading a spec file, is passed on as a note. ## Copyrights Copyright (c) 2011 Rubyworks. All Rights Reserved. -RSpecOnTap is distributable in accordance with the *FreeBSD* license. +RSpec On Tap is distributable in accordance with the *BSD-2-Clause* +license. See LICENSE.txt for details. - diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..bb248e8 --- /dev/null +++ b/Rakefile @@ -0,0 +1,22 @@ +require 'rake/clean' +CLOBBER.include 'pkg' + +require 'bundler/gem_helper' + +# Bundler tags releases as v1.2.3, but RSpec On Tap's tags have always been +# plain version numbers, so keep it that way. +class Bundler::GemHelper + def version_tag + version.to_s + end +end + +Bundler::GemHelper.install_tasks + +desc 'run demos' +task 'demo' do + sh 'qed -Ilib demo/' +end + +task 'test' => 'demo' +task 'default' => 'demo' diff --git a/demo/01_tapy.md b/demo/01_tapy.md new file mode 100644 index 0000000..2a2c22b --- /dev/null +++ b/demo/01_tapy.md @@ -0,0 +1,104 @@ +# TAP-Y + +Given a spec file: + + RSpec.describe "Example" do + it "passes" do + expect(1).to eq(1) + end + + it "fails" do + expect(1).to eq(2) + end + + it "errors" do + raise NameError, "oops" + end + end + +Running it with the `RSpec::TapY` formatter gives a TAP-Y stream. RSpec +finds the formatter by its name, so nothing has to be required. + + stream = run_tapy + +There are six documents in it. + + stream.size #=> 6 + +The first is the `suite`, with the number of examples. + + stream.first['type'] #=> 'suite' + stream.first['count'] #=> 3 + stream.first['rev'] #=> 4 + +The second is a `case`, for the example group. + + stream[1]['type'] #=> 'case' + stream[1]['subtype'] #=> 'describe' + stream[1]['label'] #=> 'Example' + stream[1]['level'] #=> 0 + +The next three are the examples. + + tests = tests(stream) + + tests.keys #=> ['passes', 'fails', 'errors'] + +Each says where it is in the spec file. + + passing = tests['passes'] + + passing['status'] #=> 'pass' + passing['subtype'] #=> 'it' + passing['file'] #=> './spec/example_spec.rb' + passing['line'] #=> 2 + passing['source'] #=> 'it "passes" do' + + passing.key?('exception') #=> false + +An expectation that isn't met is a failure. It says what was expected +and what came back, and where. + + failing = tests['fails'] + + failing['status'] #=> 'fail' + failing['expected'] #=> '2' + failing['returned'] #=> '1' + + failing['exception']['class'] #=> 'RSpec::Expectations::ExpectationNotMetError' + failing['exception']['file'] #=> './spec/example_spec.rb' + failing['exception']['line'] #=> 7 + failing['exception']['source'] #=> 'expect(1).to eq(2)' + + failing['exception']['message'].assert.include?('expected: 2') + +It comes with the lines around the failure. + + failing['exception']['snippet'].map { |line| line.keys.first } #=> [5, 6, 7, 8, 9] + failing['exception']['snippet'][2][7] #=> ' expect(1).to eq(2)' + +Anything else raised is an error. + + erring = tests['errors'] + + erring['status'] #=> 'error' + erring['exception']['class'] #=> 'NameError' + erring['exception']['message'] #=> 'oops' + erring['exception']['line'] #=> 11 + + erring['exception']['backtrace'].first.assert.start_with?('./spec/example_spec.rb:11') + +The last document is the `final` one, with the counts. + + stream.last['type'] #=> 'final' + stream.last['counts'] #=> {'total'=>3, 'pass'=>1, 'fail'=>1, 'error'=>1, 'omit'=>0, 'todo'=>0} + +The stream ends with the YAML end-of-document marker. + + @stdout.lines.last #=> "...\n" + +Nothing else is written, and the exit status still tells of the +failures. + + @stderr #=> '' + @status.success? #=> false diff --git a/demo/02_tapj.md b/demo/02_tapj.md new file mode 100644 index 0000000..7b571ab --- /dev/null +++ b/demo/02_tapj.md @@ -0,0 +1,35 @@ +# TAP-J + +Given a spec file: + + RSpec.describe "Example" do + it "passes" do + expect(1).to eq(1) + end + + it "fails" do + expect(1).to eq(2) + end + end + +The `RSpec::TapJ` formatter gives a TAP-J stream: the same records as +TAP-Y, as a JSON document on each line. + + stream = run_tapj + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'test', 'final'] + + tests = tests(stream) + + tests['passes']['status'] #=> 'pass' + tests['fails']['status'] #=> 'fail' + tests['fails']['exception']['file'] #=> './spec/example_spec.rb' + tests['fails']['exception']['line'] #=> 7 + + stream.last['counts'] #=> {'total'=>2, 'pass'=>1, 'fail'=>1, 'error'=>0, 'omit'=>0, 'todo'=>0} + +The formatters can also be loaded by requiring `rspec/ontap`. + + stream = run_specs('-r', 'rspec/ontap', '-f', 'RSpec::TapJ').lines + + stream.size #=> 5 diff --git a/demo/03_pending.md b/demo/03_pending.md new file mode 100644 index 0000000..b8832f0 --- /dev/null +++ b/demo/03_pending.md @@ -0,0 +1,57 @@ +# Skipped and pending examples + +Given a spec file: + + RSpec.describe "Example" do + it "is skipped" do + skip "not on this machine" + end + + xit "is crossed out" do + expect(1).to eq(2) + end + + it "is pending" do + pending "waiting on a fix" + expect(1).to eq(2) + end + + it "is yet to be written" + + it "was pending" do + pending "waiting on a fix" + expect(1).to eq(1) + end + end + +RSpec calls all of the first four pending. TAP-Y/J tells them apart. + + stream = run_tapy + tests = tests(stream) + +An example that was skipped is omitted, with the reason. + + tests['is skipped']['status'] #=> 'omit' + tests['is skipped']['exception']['message'] #=> 'not on this machine' + + tests['is crossed out']['status'] #=> 'omit' + tests['is crossed out']['exception']['message'] #=> 'Temporarily skipped with xit' + +An example that is pending, or has no body yet, is still to be done. + + tests['is pending']['status'] #=> 'todo' + tests['is pending']['exception']['message'] #=> 'waiting on a fix' + + tests['is yet to be written']['status'] #=> 'todo' + tests['is yet to be written']['exception']['message'] #=> 'Not yet implemented' + +A pending example that passes is a failure, as it is to RSpec, and not +an error. + + tests['was pending']['status'] #=> 'fail' + + tests['was pending']['exception']['message'].assert.include?('it passed') + +The counts agree. + + stream.last['counts'] #=> {'total'=>5, 'pass'=>0, 'fail'=>1, 'error'=>0, 'omit'=>2, 'todo'=>2} diff --git a/demo/04_details.md b/demo/04_details.md new file mode 100644 index 0000000..06a3d24 --- /dev/null +++ b/demo/04_details.md @@ -0,0 +1,115 @@ +# Details + +## Nested groups + +Given a spec file: + + RSpec.describe "Outer" do + it "one" do + expect(1).to eq(1) + end + + context "inner" do + it "two" do + expect(2).to eq(2) + end + + describe "innermost" do + it "three" do + expect(3).to eq(3) + end + end + end + end + + RSpec.describe "Another" do + it "four" do + expect(4).to eq(4) + end + end + +Each group is a case, and its level says how deep it is. + + stream = run_tapy + + cases = stream.select { |d| d['type'] == 'case' } + + cases.map { |d| [d['label'], d['level']] } #=> [['Outer', 0], ['inner', 1], ['innermost', 2], ['Another', 0]] + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'case', 'test', 'case', 'test', 'case', 'test', 'final'] + +## Output from examples + +Given a spec file: + + RSpec.describe "Example" do + it "is noisy" do + puts "to stdout" + warn "to stderr" + end + + it "is quiet" do + end + + it "is noisy and fails" do + puts "before failing" + expect(1).to eq(2) + end + end + +What an example prints would break the stream. It is captured and +becomes part of the example's record. + + stream = run_tapy + tests = tests(stream) + + tests['is noisy']['stdout'] #=> 'to stdout' + tests['is noisy']['stderr'] #=> 'to stderr' + + tests['is quiet'].key?('stdout') #=> false + tests['is quiet'].key?('stderr') #=> false + + tests['is noisy and fails']['stdout'] #=> 'before failing' + + @stderr #=> '' + +## The seed + +When the examples run in random order, the seed is in the `suite` +document. + + stream = run_tapy('--seed', '42') + + stream.first['seed'] #=> 42 + +Otherwise there is none. + + stream = run_tapy + + stream.first['seed'] #=> nil + +## A spec file that can't be loaded + +Given a spec file: + + RSpec.describe "Example" do + it "passes" do + expect(1).to eq(1) + end + end + + raise "can't go on" + +What RSpec has to say about it becomes a note, after the `suite` +document that has to begin the stream. (RSpec reports such an error +from version 3.6. Before that it let the error end the run.) + + if Gem.loaded_specs['rspec-core'].version >= Gem::Version.new('3.6') + stream = run_tapy + + stream.map { |d| d['type'] }.assert == ['suite', 'note', 'final'] + + stream[1]['text'].assert.include?("can't go on") + + @status.refute.success? + end diff --git a/demo/05_tapout.md b/demo/05_tapout.md new file mode 100644 index 0000000..af9414f --- /dev/null +++ b/demo/05_tapout.md @@ -0,0 +1,45 @@ +# Tapout + +The stream is for Tapout, which renders it in a format of your choice. + +Given a spec file: + + RSpec.describe "Example" do + it "passes" do + expect(1).to eq(1) + end + + it "fails" do + expect(1).to eq(2) + end + + it "errors" do + raise NameError, "oops" + end + + it "is skipped" do + skip "not today" + end + + it "is yet to be written" + end + +Tapout reads the TAP-Y stream. + + out = tapout(run_specs('-f', 'RSpec::TapY'), 'tap') + + out.assert.include?('1..5') + + out.assert =~ /^ok 1 - passes$/ + out.assert =~ /^not ok 2 - fails$/ + out.assert =~ /^not ok 3 - errors$/ + out.assert =~ /^ok 4 - is skipped # SKIP not today$/ + out.assert =~ /^not ok 5 - is yet to be written # TODO Not yet implemented$/ + +And the TAP-J stream. + + out = tapout(run_specs('-f', 'RSpec::TapJ'), 'tap') + + out.assert =~ /^ok 1 - passes$/ + out.assert =~ /^not ok 2 - fails$/ + out.assert =~ /^ok 4 - is skipped # SKIP not today$/ diff --git a/demo/applique/ae.rb b/demo/applique/ae.rb new file mode 100644 index 0000000..84ae3d2 --- /dev/null +++ b/demo/applique/ae.rb @@ -0,0 +1 @@ +require 'ae' diff --git a/demo/applique/run.rb b/demo/applique/run.rb new file mode 100644 index 0000000..92157db --- /dev/null +++ b/demo/applique/run.rb @@ -0,0 +1,49 @@ +require 'tmpdir' +require 'open3' +require 'rbconfig' +require 'yaml' +require 'json' + +# Each demo writes a spec file and runs it with the `rspec` command, in +# a process of its own. + +LIB = File.expand_path('../../lib', __dir__) + +When 'iven a spec file' do |text| + @source = text +end + +# Run the spec file with the given command line options. Returns what +# the run wrote to standard output. +def run_specs(*options) + rspec = Gem.bin_path('rspec-core', 'rspec') + Dir.mktmpdir('rspec-ontap') do |dir| + Dir.mkdir(File.join(dir, 'spec')) + File.write(File.join(dir, 'spec', 'example_spec.rb'), @source) + command = [RbConfig.ruby, rspec, "-I#{LIB}", '--no-color', *options] + @stdout, @stderr, @status = Open3.capture3(*command, :chdir => dir) + end + @stdout +end + +# Run the spec file and read its output as a TAP-Y stream. +def run_tapy(*options) + YAML.load_stream(run_specs('-f', 'RSpec::TapY', *options)) +end + +# Run the spec file and read its output as a TAP-J stream. +def run_tapj(*options) + run_specs('-f', 'RSpec::TapJ', *options).lines.map { |line| JSON.parse(line) } +end + +# The test records of a stream, by label. +def tests(stream) + stream.select { |d| d['type'] == 'test' }.to_h { |d| [d['label'], d] } +end + +# Pipe a stream through Tapout. Returns what Tapout printed. +def tapout(stream, reporter) + bin = Gem.bin_path('tapout', 'tapout') + out, _ = Open3.capture2(RbConfig.ruby, bin, reporter, :stdin_data => stream) + out +end diff --git a/lib/rspec/ontap.rb b/lib/rspec/ontap.rb index 3971763..7109fef 100644 --- a/lib/rspec/ontap.rb +++ b/lib/rspec/ontap.rb @@ -1,512 +1,344 @@ +require 'rspec/core' require 'rspec/core/formatters/base_formatter' +require 'rspec/ontap/version' +require 'stringio' module RSpec - #module Core - #module Formatters - # + # Base class of the TAP-Y and TAP-J formatters. It turns RSpec's + # notifications into the records of a TAP-Y/J stream; the subclasses + # write them out. + # + # While an example runs, `$stdout` and `$stderr` are captured, so that + # what it prints becomes part of its record instead of breaking the + # stream. class TapBaseFormatter < Core::Formatters::BaseFormatter - # TAP-Y/J Revision + # TAP-Y/J revision. REVISION = 4 - # - attr_accessor :example_group_stack + # Number of lines of source to show on each side of a line. + SNIPPET_RADIUS = 2 + + # The notifications the formatters ask RSpec for. + NOTIFICATIONS = [ + :start, + :example_group_started, + :example_group_finished, + :example_started, + :example_passed, + :example_failed, + :example_pending, + :message, + :dump_summary, + :close + ] - # def initialize(output) super(output) - @example_group_stack = [] + # Tapout reads from a pipe, so nothing should wait in a buffer. + output.sync = true if output.respond_to?(:sync=) + @group_level = 0 + @source_cache = {} + @omit_count = 0 + @early_notes = [] end - # - # This method is invoked before any examples are run, right after - # they have all been collected. This can be useful for special - # formatters that need to provide progress on feedback (graphical ones) - # - # This will only be invoked once, and the next one to be invoked - # is #example_group_started - # + # Invoked once, before any example runs. def start(notification) - # there is a super method for this - super(notification) - + super @start_time = Time.now - - doc = { + @seed = configuration.seed if configuration.seed_used? + emit( 'type' => 'suite', 'start' => @start_time.strftime('%Y-%m-%d %H:%M:%S'), 'count' => notification.count, 'seed' => @seed, 'rev' => REVISION - } - return doc + ) + @early_notes.each { |note| emit note } + @early_notes = nil end - # - # This method is invoked at the beginning of the execution of each example group. - # +example_group+ is the example_group. - # - # The next method to be invoked after this is +example_passed+, - # +example_pending+, or +example_finished+ - # + # Invoked at the start of each example group. def example_group_started(notification) - # there is a super method for this - super(notification) - doc = { + super + emit( 'type' => 'case', 'subtype' => 'describe', - 'label' => "#{notification.group.description}", - 'level' => @example_group_stack.size - } - @example_group_stack << example_group - return doc + 'label' => notification.group.description.to_s, + 'level' => @group_level + ) + @group_level += 1 end - # This method is invoked at the end of the execution of each example group. - # +example_group+ is the example_group. + # Invoked at the end of each example group. def example_group_finished(notification) - #super(notification) - @example_group_stack.pop + @group_level -= 1 end - # Set up stdout and stderr to be captured. - # - # IMPORTANT: Comment out the `reset_output` line to debug!!!!!!!!! - # + # Invoked before each example. Starts capturing its output. def example_started(notification) - reset_output + capture_output end # def example_passed(notification) - #super(notification) - - example = notification.example - - file, line = example.location.split(':') - #file = self.class.relative_path(file) - file = relative_path(file) - line = line.to_i - - doc = { - 'type' => 'test', - 'subtype' => 'it', - 'status' => 'pass', - #'setup': foo instance - 'label' => "#{example.description}", - #'expected' => 2 - #'returned' => 2 - 'file' => file, - 'line' => line, - 'source' => source(file)[line-1].strip, - 'snippet' => code_snippet(file, line), - #'coverage' => { - # file: lib/foo.rb - # line: 11..13 - # code: Foo#* - #} - 'time' => Time.now - @start_time - } - - doc.update(captured_output) - - return doc + emit test_record(notification.example, 'pass') end + # Invoked for an example that was skipped or is pending. # + # An example that was skipped (`skip`, `xit`) is an `omit` in + # TAP-Y/J. One that is pending, or has no body yet, is a `todo`. def example_pending(notification) - #super(notification) - example = notification.example + reason = example.execution_result.pending_message.to_s - file, line = example.location.split(':') - #file = self.class.relative_path(file) - file = relative_path(file) - line = line.to_i - - doc = { - 'type' => 'test', - 'subtype' => 'it', - 'status' => 'todo', - #'setup': foo instance - 'label' => "#{example.description}", - 'file' => file, - 'line' => line, - 'source' => source(file)[line-1].strip, - 'snippet' => code_snippet(file, line), - #'coverage' => { - # file: lib/foo.rb - # line: 11..13 - # code: Foo#* - #} - 'time' => Time.now - @start_time - } - - doc.update(captured_output) + if example.skipped? && reason != Core::Pending::NOT_YET_IMPLEMENTED + status = 'omit' + @omit_count += 1 + else + status = 'todo' + end - return doc + record = test_record(example, status) + record['exception'] = { 'message' => reason } unless reason.empty? + emit record end # def example_failed(notification) - #super(notification) - - example = notification.example - - file, line = example.location.split(':') - - file = relative_path(file) - line = line.to_i - - if RSpec::Expectations::ExpectationNotMetError === example.exception - status = 'fail' - if md = /expected:\s*(.*?)\n\s*got:\s*(.*?)\s+/.match(example.exception.to_s) - expected, returned = md[1], md[2] - else - expected, returned = nil, nil - end - else - status = 'error' - end - - backtrace = format_backtrace(example.exception.backtrace, example.metadata) - - efile, eline = parse_source_location(backtrace) - - doc = { - 'type' => 'test', - 'subtype' => 'it', - 'status' => status, - 'label' => "#{example.description}", - #'setup' => "foo instance", - 'file' => file, - 'line' => line, - 'source' => source(file)[line-1].strip, - 'snippet' => code_snippet(file, line), - #'coverage' => - #{ - # 'file' => lib/foo.rb - # 'line' => 11..13 - # 'code' => Foo#* - #} - } + example = notification.example + exception = example.exception + record = test_record(example, failure?(exception) ? 'fail' : 'error') - if expected or returned - doc.update( - 'expected' => expected, - 'returned' => returned, - ) + if md = /expected:\s*(.*?)\n\s*got:\s*(.*?)\s+/.match(exception.to_s) + record['expected'] = md[1] + record['returned'] = md[2] end - doc.update( - 'exception' => { - 'message' => example.exception.to_s.strip, - 'class' => example.exception.class.name, - 'file' => efile, - 'line' => eline, - 'source' => source(efile)[eline-1].strip, - 'snippet' => code_snippet(efile, eline), - 'backtrace' => backtrace - }, - 'time' => Time.now - @start_time - ) - - doc.update(captured_output) - - return doc + record['exception'] = exception_record(example, exception) + emit record end - # This method is invoked after the dumping of examples and failures. - def dump_summary(summary_notification) - #super(summary_notification) - - duration = summary_notification.duration - example_count = summary_notification.examples.size - failure_count = summary_notification.failed_examples.size - pending_count = summary_notification.pending_examples.size - - failed_examples = summary_notification.failed_examples - - error_count = 0 - - failed_examples.each do |e| - if RSpec::Expectations::ExpectationNotMetError === e.exception - #failure_count += 1 - else - failure_count -= 1 - error_count += 1 - end - end + # Invoked for anything RSpec has to say outside of an example, such + # as an error while loading a spec file. It becomes a note. + def message(notification) + text = notification.message.to_s.strip + return if text.empty? + note = { 'type' => 'note', 'text' => text } + # The stream has to begin with the suite, so a note that comes + # before it waits. + @early_notes ? @early_notes << note : emit(note) + end - passing_count = example_count - failure_count - error_count - pending_count + # Invoked when all examples have run. + def dump_summary(summary) + total = summary.examples.size + failed = summary.failed_examples + failures = failed.count { |example| failure?(example.exception) } + errors = failed.size - failures + pending = summary.pending_examples.size - doc = { - 'type' => 'final', - 'time' => duration, + emit( + 'type' => 'final', + 'time' => summary.duration, 'counts' => { - 'total' => example_count, - 'pass' => passing_count, - 'fail' => failure_count, - 'error' => error_count, - 'omit' => 0, - 'todo' => pending_count + 'total' => total, + 'pass' => total - failed.size - pending, + 'fail' => failures, + 'error' => errors, + 'omit' => @omit_count, + 'todo' => pending - @omit_count } - } - return doc - end - - # This gets invoked after the summary if option is set to do so. - #def dump_pending - #end - - def seed(notification) - @seed = notification.seed + ) + finish end - # Add any messages as notes. - def message(message_notification) - doc = { - 'type' => 'note', - 'text' => message_notification.message - } - return doc + # Invoked last. Makes sure the real output streams are back. + def close(notification) + release_output + super end - # - # NOTE: None of the following are being used. If ever added, be sure - # to activate in register calls below. - # + private - # (not used) - def stop(examples_notification) - super(examples_notification) + # Write a record to the stream. Subclasses define this. + def emit(record) + raise NotImplementedError end - # (not used) - def start_dump(null_notification) + # Write whatever ends the stream. + def finish end - # (not used) - def dump_pending(examples_notification) - end + # What every test record has: where the example is and what it + # printed. + def test_record(example, status) + record = { + 'type' => 'test', + 'subtype' => 'it', + 'status' => status, + 'label' => example.description.to_s + } - # (not used) - def dump_failures(examples_notification) - end + file, line = split_location(example.location) + if file + record['file'] = file + record['line'] = line + add_source(record, file, line) + end - # (not used) - def close(null_notification) - # there is a super method for this - super(null_notification) + record.update(captured_output) + record['time'] = Time.now - @start_time + record end - private + # + def exception_record(example, exception) + backtrace = format_backtrace(exception.backtrace || [], example.metadata) + file, line = split_location(backtrace.first) - # Returns a String of source code. - def code_snippet(file, line) - s = [] - if File.file?(file) - source = source(file) - radius = 2 # TODO: make customizable (number of surrounding lines to show) - region = [line - radius, 1].max .. - [line + radius, source.length].min - - s = region.map do |n| - {n => source[n-1].chomp} - end + record = { + 'message' => exception.to_s.strip, + 'class' => exception.class.name + } + if file + record['file'] = file + record['line'] = line + add_source(record, file, line) end - return s + record['backtrace'] = backtrace + record end - # Cache source file text. This is only used if the TAP-Y stream - # doesn not provide a snippet and the test file is locatable. - def source(file) - @_source_cache ||= {} - @_source_cache[file] ||= ( - File.readlines(file) - ) + # An expectation that wasn't met is a failure, as is a pending + # example that passed. Anything else raised is an error. + def failure?(exception) + return true if Core::Pending::PendingExampleFixedError === exception + return true if defined?(RSpec::Expectations::ExpectationNotMetError) && + RSpec::Expectations::ExpectationNotMetError === exception + return true if defined?(RSpec::Mocks::MockExpectationError) && + RSpec::Mocks::MockExpectationError === exception + false end - # Parse source location from caller, caller[0] or an Exception object. - def parse_source_location(caller) - case caller - when Exception - trace = caller.backtrace #.reject{ |bt| bt =~ INTERNALS } - caller = trace.first - when Array - caller = caller.first - end - caller =~ /(.+?):(\d+(?=:|\z))/ or return "" - source_file, source_line = $1, $2.to_i - return source_file, source_line + # Split `file:line`, with or without more after it, in two. + def split_location(location) + md = /\A(.+?):(\d+)(?::|\z)/.match(location.to_s) + md ? [relative_path(md[1]), md[2].to_i] : [nil, nil] end - # - def reset_output - @_oldout = $stdout - @_olderr = $stderr - - @_newout = StringIO.new - @_newerr = StringIO.new - - $stdout = @_newout - $stderr = @_newerr + # Add the line of source, and the lines around it, to a record. + def add_source(record, file, line) + lines = source(file) or return + record['source'] = lines[line - 1].to_s.strip + record['snippet'] = snippet(lines, line) end - # - def captured_output - return unless (@_newout && @_newerr) - - stdout = @_newout.string.chomp("\n") - stderr = @_newerr.string.chomp("\n") - - doc = {} - doc['stdout'] = stdout unless stdout.empty? - doc['stderr'] = stderr unless stderr.empty? + # The lines of a source file, or nil if it can't be read. + def source(file) + return @source_cache[file] if @source_cache.key?(file) + @source_cache[file] = File.file?(file) ? File.readlines(file) : nil + end - $stdout = @_oldout - $stderr = @_olderr + # The lines around a line of source, as a list of number => text. + def snippet(lines, line) + first = [line - SNIPPET_RADIUS, 1].max + last = [line + SNIPPET_RADIUS, lines.size].min + (first..last).map { |n| { n => lines[n - 1].chomp } } + end - return doc + # A path under the working directory, written from `./`. + def relative_path(path) + directory = File.expand_path('.') + File::SEPARATOR + path.start_with?(directory) ? './' + path[directory.size..-1] : path end # - def capture_io - ostdout, ostderr = $stdout, $stderr - cstdout, cstderr = StringIO.new, StringIO.new - $stdout, $stderr = cstdout, cstderr - - yield - - return cstdout.string.chomp("\n"), cstderr.string.chomp("\n") - ensure - $stdout = ostdout - $stderr = ostderr + def format_backtrace(backtrace, metadata) + configuration.backtrace_formatter.format_backtrace(backtrace, metadata) end # - def relative_path_regex - @relative_path_regex ||= /(\A|\s)#{File.expand_path('.')}(#{File::SEPARATOR}|\s|\Z)/ + def configuration + RSpec.configuration end - # Get relative path of file. - # - # line - current code line [String] # - # Returns relative path to line. [String] - def relative_path(line) - line = line.sub(relative_path_regex, "\\1.\\2".freeze) - line = line.sub(/\A([^:]+:\d+)$/, '\\1'.freeze) - return nil if line == '-e:1'.freeze - line - rescue SecurityError - nil + def capture_output + release_output + @real_stdout, @real_stderr = $stdout, $stderr + @stdout, @stderr = StringIO.new, StringIO.new + $stdout, $stderr = @stdout, @stderr end - # - def format_backtrace(*args) - backtrace_formatter.format_backtrace(*args) + # Put back the real output streams, unless the example changed them + # itself. + def release_output + return unless @stdout + $stdout = @real_stdout if $stdout.equal?(@stdout) + $stderr = @real_stderr if $stderr.equal?(@stderr) + @stdout = @stderr = nil end - # - def backtrace_formatter - RSpec.configuration.backtrace_formatter + # What the example printed, as part of a record. + def captured_output + return {} unless @stdout + + stdout = @stdout.string.chomp("\n") + stderr = @stderr.string.chomp("\n") + release_output + + record = {} + record['stdout'] = stdout unless stdout.empty? + record['stderr'] = stderr unless stderr.empty? + record end end + # Formats in TAP-Y, a stream of YAML documents. + # + # $ rspec -f RSpec::TapY | tapout # class TapY < TapBaseFormatter - ::RSpec::Core::Formatters.register self, - :start, - :example_group_started, - :example_group_finished, - :example_started, - :example_passed, - :example_failed, - :example_pending, - :dump_summary, - :seed, - :message, - #:stop, - #:start_dump, - #:dump_pending, - #:dump_failures, - :close - - def initialize(*args) + Core::Formatters.register self, *NOTIFICATIONS + + def initialize(output) require 'yaml' - super(*args) + super end - def start(*args) - output.puts super(*args).to_yaml - end - def example_group_started(*args) - output.puts super(*args).to_yaml - end - def example_passed(*args) - output.puts super(*args).to_yaml - end - def example_pending(*args) - output.puts super(*args).to_yaml - end - def example_failed(*args) - output.puts super(*args).to_yaml + + private + + def emit(record) + output.puts record.to_yaml end - #def dump_summary(duration, example_count, failure_count, pending_count) - # output.puts super(duration, example_count, failure_count, pending_count).to_yaml - # output.puts "..." - #end - def dump_summary(*args) - output.puts super(*args).to_yaml - output.puts "..." + + def finish + output.puts '...' end end - #rspec -f RSpec::TapY spec/*.rb | tapout progress + # Formats in TAP-J, a JSON document on each line. + # + # $ rspec -f RSpec::TapJ | tapout + # class TapJ < TapBaseFormatter - ::RSpec::Core::Formatters.register self, - :start, - :example_group_started, - :example_group_finished, - :example_started, - :example_passed, - :example_failed, - :example_pending, - :dump_summary, - :seed, - :message, - #:stop, - #:start_dump, - #:dump_pending, - #:dump_failures, - :close - - def initialize(*args) + Core::Formatters.register self, *NOTIFICATIONS + + def initialize(output) require 'json' - super(*args) - end - def start(*args) - output.puts super(*args).to_json - end - def example_group_started(*args) - output.puts super(*args).to_json + super end - def example_passed(*args) - output.puts super(*args).to_json - end - def example_pending(*args) - output.puts super(*args).to_json - end - def example_failed(*args) - output.puts super(*args).to_json - end - def dump_summary(*args) - output.puts super(*args).to_json + + private + + def emit(record) + output.puts JSON.generate(record) end end - #end - #end end diff --git a/lib/rspec/ontap/version.rb b/lib/rspec/ontap/version.rb new file mode 100644 index 0000000..221ed4e --- /dev/null +++ b/lib/rspec/ontap/version.rb @@ -0,0 +1,5 @@ +module RSpec + module OnTap + VERSION = '0.4.0' + end +end diff --git a/lib/rspec/tap_j.rb b/lib/rspec/tap_j.rb index 3f7c715..a9c5689 100644 --- a/lib/rspec/tap_j.rb +++ b/lib/rspec/tap_j.rb @@ -1,5 +1,2 @@ -if RUBY_VERSION < '1.9' - require File.dirname(__FILE__) + '/ontap' -else - require_relative 'ontap' -end +# RSpec requires this file when asked for the formatter RSpec::TapJ. +require_relative 'ontap' diff --git a/lib/rspec/tap_y.rb b/lib/rspec/tap_y.rb index 3f7c715..f88dcf4 100644 --- a/lib/rspec/tap_y.rb +++ b/lib/rspec/tap_y.rb @@ -1,5 +1,2 @@ -if RUBY_VERSION < '1.9' - require File.dirname(__FILE__) + '/ontap' -else - require_relative 'ontap' -end +# RSpec requires this file when asked for the formatter RSpec::TapY. +require_relative 'ontap' diff --git a/rspec-ontap.gemspec b/rspec-ontap.gemspec new file mode 100644 index 0000000..20cb569 --- /dev/null +++ b/rspec-ontap.gemspec @@ -0,0 +1,39 @@ +require_relative 'lib/rspec/ontap/version' + +Gem::Specification.new do |s| + s.name = 'rspec-ontap' + s.version = RSpec::OnTap::VERSION + s.summary = 'TAP-Y/J formatters for RSpec' + s.description = 'RSpec On Tap is a pair of RSpec formatters that report in TAP-Y ' \ + 'or TAP-J, for Tapout to render in any of its formats.' + + s.authors = ['Trans'] + s.email = ['transfire@gmail.com'] + s.homepage = 'https://github.com/rubyworks/rspec-ontap' + s.license = 'BSD-2-Clause' + + s.metadata = { + 'homepage_uri' => s.homepage, + 'source_code_uri' => 'https://github.com/rubyworks/rspec-ontap', + 'bug_tracker_uri' => 'https://github.com/rubyworks/rspec-ontap/issues', + 'changelog_uri' => 'https://github.com/rubyworks/rspec-ontap/blob/master/HISTORY.md', + 'documentation_uri' => 'https://rubydoc.info/gems/rspec-ontap' + } + + s.required_ruby_version = '>= 2.7' + + s.files = Dir[ + 'lib/**/*.rb', 'demo/**/*', + '.yardopts', 'README.md', 'HISTORY.md', 'LICENSE.txt' + ] + s.require_paths = ['lib'] + s.extra_rdoc_files = ['HISTORY.md', 'README.md', 'LICENSE.txt'] + + s.add_dependency 'rspec', '>= 3.0', '< 4' + s.add_dependency 'tapout', '>= 0.5' + s.add_dependency 'json' + + s.add_development_dependency 'rake', '>= 13' + s.add_development_dependency 'qed', '>= 2.9' + s.add_development_dependency 'ae', '>= 1.8' +end diff --git a/try/spec_example.rb b/try/spec_example.rb deleted file mode 100644 index fccda5e..0000000 --- a/try/spec_example.rb +++ /dev/null @@ -1,20 +0,0 @@ -describe "demonstration" do - - it "should show this passing" do - expect(1).to == 1 - end - - it "should show this failing" do - expect(1).to == 2 - end - - it "should show this raising an error" do - raise NameError - end - - it "should capture stdout" do - puts "HELLO!" - end - -end - From 7551dd960812d117246628c553e816da8b28da2d Mon Sep 17 00:00:00 2001 From: Thomas Sawyer Date: Sat, 21 Nov 2026 23:17:37 -0500 Subject: [PATCH 2/2] Use an error in the demo whose message Ruby 3.1 leaves alone Ruby 3.1 appends the highlighted source line to a NameError's message. Co-Authored-By: Claude Fable 5.2 --- demo/01_tapy.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/demo/01_tapy.md b/demo/01_tapy.md index 2a2c22b..91b7b24 100644 --- a/demo/01_tapy.md +++ b/demo/01_tapy.md @@ -12,7 +12,7 @@ Given a spec file: end it "errors" do - raise NameError, "oops" + raise "oops" end end @@ -82,7 +82,7 @@ Anything else raised is an error. erring = tests['errors'] erring['status'] #=> 'error' - erring['exception']['class'] #=> 'NameError' + erring['exception']['class'] #=> 'RuntimeError' erring['exception']['message'] #=> 'oops' erring['exception']['line'] #=> 11