|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "spec_helper" |
| 4 | + |
| 5 | +RSpec.describe "Stdout matcher value capture" do |
| 6 | + let(:formatter) { RSpec::EnrichedJson::Formatters::EnrichedJsonFormatter.new(StringIO.new) } |
| 7 | + |
| 8 | + # Use the same Oj options for loading that we use for dumping |
| 9 | + let(:oj_load_options) do |
| 10 | + { |
| 11 | + mode: :object, |
| 12 | + symbol_keys: true, |
| 13 | + auto_define: false, |
| 14 | + create_additions: false |
| 15 | + } |
| 16 | + end |
| 17 | + |
| 18 | + it "captures actual when spec passes" do |
| 19 | + test_file = "spec/support/stdout_passing_spec.rb" |
| 20 | + File.write(test_file, <<~RUBY) |
| 21 | + RSpec.describe "Test" do |
| 22 | + it "checks output" do |
| 23 | + expect { puts "Hello" }.to output("Hello\\n").to_stdout |
| 24 | + end |
| 25 | + end |
| 26 | + RUBY |
| 27 | + |
| 28 | + output = run_rspec(test_file) |
| 29 | + json = Oj.load(output) |
| 30 | + example = json["examples"].first |
| 31 | + |
| 32 | + expect(example["details"]["expected"]).to eq("\"Hello\\n\"") |
| 33 | + expect(example["details"]["actual"]).to eq("Hello\n") |
| 34 | + ensure |
| 35 | + File.delete(test_file) if File.exist?(test_file) |
| 36 | + end |
| 37 | + |
| 38 | + it "captures actual when spec fails" do |
| 39 | + test_file = "spec/support/stdout_passing_spec.rb" |
| 40 | + File.write(test_file, <<~RUBY) |
| 41 | + RSpec.describe "Test" do |
| 42 | + it "checks output" do |
| 43 | + expect { puts "Hello" }.to output("Bye\\n").to_stdout |
| 44 | + end |
| 45 | + end |
| 46 | + RUBY |
| 47 | + |
| 48 | + output = run_rspec(test_file) |
| 49 | + json = Oj.load(output) |
| 50 | + example = json["examples"].first |
| 51 | + |
| 52 | + expect(example["details"]["expected"]).to eq("\"Bye\\n\"") |
| 53 | + expect(example["details"]["actual"]).to eq("\"Hello\\n\"") |
| 54 | + ensure |
| 55 | + File.delete(test_file) if File.exist?(test_file) |
| 56 | + end |
| 57 | + |
| 58 | + private |
| 59 | + |
| 60 | + def run_rspec(test_file) |
| 61 | + output = nil |
| 62 | + Dir.mktmpdir do |dir| |
| 63 | + output_file = File.join(dir, "output.json") |
| 64 | + cmd = "bundle exec rspec #{test_file} --format RSpec::EnrichedJson::Formatters::EnrichedJsonFormatter --out #{output_file} 2>&1" |
| 65 | + system(cmd, out: File::NULL) |
| 66 | + output = File.read(output_file) |
| 67 | + end |
| 68 | + output |
| 69 | + end |
| 70 | +end |
0 commit comments