diff --git a/README.md b/README.md index 19e28e5..7b3d488 100644 --- a/README.md +++ b/README.md @@ -2,23 +2,10 @@ [![Code Climate](https://codeclimate.com/github/codeclimate/ruby-test-reporter/badges/gpa.svg)](https://codeclimate.com/github/codeclimate/ruby-test-reporter) -Collects test coverage data from your Ruby test suite and sends it to Code -Climate's hosted, automated code review service. Based on SimpleCov. +Posts SimpleCov test coverage data from your Ruby test suite to Code Climate's hosted, automated code review service. Code Climate - [https://codeclimate.com](https://codeclimate.com) -# Important FYIs - -Across the many different testing frameworks, setups, and environments, there are lots of variables at play. Before setting up test coverage, it's important to understand what we do and do not currently support: - -* **Default branch only:** We only support test coverage for your [default branch](http://docs.codeclimate.com/article/151-glossary-default-branch). Be sure to check out this branch before running your tests. -* **Single payload:** We currently only support a single test coverage payload per commit. If you run your tests in multiple steps, or via parallel tests, Code Climate will only process the first payload that we receive. If you are using a CI, be sure to check if you are running your tests in a parallel mode. - - **Note:** There is one exception to this rule. We've specifically built an integration with [Solano Labs](https://www.solanolabs.com/) to support parallel tests. - - **Note:** If you've configured Code Climate to analyze multiple languages in the same repository (e.g., Ruby and JavaScript), we can nonetheless only process test coverage information for one of these languages. We'll process the first payload that we receive. -* **Invalid File Paths:** By default, our test reporters expect your application to exist at the root of your repository. If this is not the case, the file paths in your test coverage payload will not match the file paths that Code Climate expects. For our Ruby test reporter, [we have a work-around to this issue](http://docs.codeclimate.com/article/220-help-im-having-trouble-with-test-coverage#ruby_sub_folder). - ## Installation This gem requires a user, but not necessarily a paid account, on Code Climate, so if you don't have one the @@ -28,130 +15,17 @@ first step is to signup at: [https://codeclimate.com](https://codeclimate.com). gem "codeclimate-test-reporter", group: :test -1. Start the test reporter **on the very first line** of your `test_helper.rb` or - `spec_helper.rb` file: - - require "codeclimate-test-reporter" - CodeClimate::TestReporter.start +1. Start SimpleCov as you normally would (more information here: https://github.com/colszowka/simplecov) -Then set the `CODECLIMATE_REPO_TOKEN` environment variable when you run your build -on your CI server, and the results will show up in your Code Climate account. +1. Set the `CODECLIMATE_REPO_TOKEN` environment variable (provided after you add your repo to your Code Climate account by clicking on "Setup Test Coverage" on the right hand side of your feed) -The `CODECLIMATE_REPO_TOKEN` value is provided after you add your repo to your -Code Climate account by clicking on "Setup Test Coverage" on the right hand side of your feed. +1. Run the `codeclimate-test-reporter` executable at the end of your test suite Please contact hello@codeclimate.com if you need any assistance setting this up. -## Configuration - -Certain behaviors of the test reporter can be configured. See the `Configuration` -class for more details. For example, you can change the logging level to not -print info messages: - -*Note that the configuration block must come before TestReporter.start.* - -```ruby -CodeClimate::TestReporter.configure do |config| - config.logger.level = Logger::WARN -end - -CodeClimate::TestReporter.start -``` - -Another example for when your Rails application root is not at the root of the git repository root - -```ruby -CodeClimate::TestReporter.configure do |config| - config.path_prefix = "app_root" #the root of your Rails application relative to the repository root - config.git_dir = "../" #the relative or absolute location of your git root compared to where your tests are run -end - -CodeClimate::TestReporter.start -``` - -## Troubleshooting - -If you're having trouble setting up or working with our test coverage feature, [see our detailed help doc](http://docs.codeclimate.com/article/220-help-im-having-trouble-with-test-coverage), which covers the most common issues encountered. - -## Extending Simplecov with other formatters - -Since ruby-test-reporter 0.4.0 you can use `CodeClimate::TestReporter::Formatter` as a Simplecov formatter directly. Just add the formatter to your Simplecov formatter in addition to the rest of your configuration: - -```ruby -require 'codeclimate-test-reporter' -SimpleCov.start do - formatter SimpleCov::Formatter::MultiFormatter.new([ - SimpleCov::Formatter::HTMLFormatter, - CodeClimate::TestReporter::Formatter - ]) - ... -end -``` - -## Using with [parallel_tests](https://github.com/grosser/parallel_tests) - -Note: This may work with other parallel test runners as long as they run on the same machine. - -Be sure you're using `simplecov` `>= 0.9.0`. - -Add the following to your `test_helper.rb`/`spec_helper.rb` instead of what is normally required. - -```ruby -require 'simplecov' -require 'codeclimate-test-reporter' -SimpleCov.add_filter 'vendor' -SimpleCov.formatters = [] -SimpleCov.start CodeClimate::TestReporter.configuration.profile -``` - -Then after all your tests run, in a rake task or as a build step do: - -``` -require 'simplecov' -require 'codeclimate-test-reporter' -CodeClimate::TestReporter::Formatter.new.format(SimpleCov.result) -``` - -## Using with multiple machines - -For the time-being, we don't officially support coverage data from parallel test runs. That said, [codeclimate batch](https://github.com/grosser/codeclimate_batch) is a handy work-around that was created by one of our customers. - -Note that this solution requires standing up a separate server (like a Heroku instance) that sits between your testing environment and Code Climate. Though this option is not formally supported, if you have an immediate need for parallel testing support, [codeclimate batch](https://github.com/grosser/codeclimate_batch) is a helpful interim solution until we can release our official support for this. - -## Help! Your gem is raising a ... - -### VCR::Errors::UnhandledHTTPRequestError - -Add the following to your spec or test helper: - - VCR.configure do |config| - # your existing configuration - config.ignore_hosts 'codeclimate.com' - end - -### WebMock::NetConnectNotAllowedError - -Add the following to your spec or test helper: - - WebMock.disable_net_connect!(:allow => "codeclimate.com") - -### Gem::InstallError: json requires Ruby version ~> 2.0 - -Some versions of simplecov after 0.11.2 effectively don't support ruby 1.9.3 -due to a loose json dependency that picks the latest version of `json`. - -See full explanation of issue: [colszowka/simplecov#511](https://github.com/colszowka/simplecov/issues/511) - -The Code Climate Ruby test reporter supports ruby > 1.9. To run with ruby less -than 2.0, you may need to specify a locked dependency to simplecov 0.11.2 or -json < 2.0 in your project's gemfile: - - gem "codeclimate-test-reporter" - gem "simplecov", "~> 0.11.2" - -### Other communication failures +## Troubleshooting / FYIs -If you are using a web stubbing library similar to VCR or WebMock which prevent external requests during test runs, you will need configure these libraries to allow Code Climate to make external requests. +Across the many different testing frameworks, setups, and environments, there are lots of variables at play. If you're having any trouble with your test coverage reporting or the results are confusing, please see our full documentation here: https://docs.codeclimate.com/docs/setting-up-test-coverage ## Contributions diff --git a/bin/codeclimate-test-reporter b/bin/codeclimate-test-reporter new file mode 100755 index 0000000..c7e7ed5 --- /dev/null +++ b/bin/codeclimate-test-reporter @@ -0,0 +1,24 @@ +#!/usr/bin/env ruby + +require "codeclimate-test-reporter" + +COVERAGE_FILE = "coverage/.resultset.json".freeze + +if ENV["CODECLIMATE_REPO_TOKEN"] + if File.exist?(COVERAGE_FILE) + begin + results = JSON.parse(File.read(COVERAGE_FILE)) + rescue JSON::ParserError => e + $stderr.puts "Error encountered while parseing #{COVERAGE_FILE}: #{e}" + exit(1) + end + + CodeClimate::TestReporter.run(results) + else + $stderr.puts "Coverage results not found" + exit(1) + end +else + $stderr.puts "Cannot post results: environment variable CODECLIMATE_REPO_TOKEN must be set." + exit(0) +end diff --git a/circle.yml b/circle.yml index eb522c6..26e23e6 100644 --- a/circle.yml +++ b/circle.yml @@ -5,3 +5,8 @@ dependencies: pre: - git config --global user.email "ci@codeclimate.com" - git config --global user.name "Code Climate CI" + +test: + override: + - bundle exec rake + - bundle exec bin/codeclimate-test-reporter diff --git a/codeclimate-test-reporter.gemspec b/codeclimate-test-reporter.gemspec index 4f12f88..28d5c45 100644 --- a/codeclimate-test-reporter.gemspec +++ b/codeclimate-test-reporter.gemspec @@ -15,7 +15,7 @@ Gem::Specification.new do |spec| spec.required_ruby_version = ">= 1.9" - spec.add_dependency "simplecov", ">= 0.7.1", "< 1.0.0" + spec.add_development_dependency "simplecov" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" diff --git a/lib/code_climate/test_reporter.rb b/lib/code_climate/test_reporter.rb index 604cf67..97a34fa 100644 --- a/lib/code_climate/test_reporter.rb +++ b/lib/code_climate/test_reporter.rb @@ -1,14 +1,23 @@ module CodeClimate module TestReporter + WARNING_MESSAGE = <<-EOS.freeze + This usage of the Code Climate Test Reporter is now deprecated. Since version + 1.0, we now require you to run `SimpleCov` in your test/spec helper, and then + run the provided `codeclimate-ruby` binary separately to report your results + to Code Climate. + + More information here: https://github.com/codeclimate/ruby-test-reporter/blob/master/README.md + EOS + def self.start - if run? - require "simplecov" - ::SimpleCov.add_filter "vendor" - ::SimpleCov.formatter = Formatter - ::SimpleCov.start(configuration.profile) do - skip_token CodeClimate::TestReporter.configuration.skip_token - end - end + logger.warn(WARNING_MESSAGE) + exit(1) + end + + def self.run(results) + return unless CodeClimate::TestReporter.run? + formatted_results = CodeClimate::TestReporter::Formatter.new.format(results) + CodeClimate::TestReporter::PostResults.new(formatted_results).post end def self.run? @@ -50,5 +59,13 @@ def self.current_branch def self.logger CodeClimate::TestReporter.configuration.logger end + + def self.tddium? + ci_service_data && ci_service_data[:name] == "tddium" + end + + def self.ci_service_data + Ci.service_data + end end end diff --git a/lib/code_climate/test_reporter/client.rb b/lib/code_climate/test_reporter/client.rb index 537a897..159532e 100644 --- a/lib/code_climate/test_reporter/client.rb +++ b/lib/code_climate/test_reporter/client.rb @@ -6,7 +6,7 @@ module CodeClimate module TestReporter class Client DEFAULT_TIMEOUT = 5 # in seconds - USER_AGENT = "Code Climate (Ruby Test Reporter v#{VERSION})".freeze + USER_AGENT = "Code Climate (Ruby Test Reporter v#{CodeClimate::TestReporter::VERSION})".freeze def host ENV["CODECLIMATE_API_HOST"] || diff --git a/lib/code_climate/test_reporter/formatter.rb b/lib/code_climate/test_reporter/formatter.rb index c1dd012..bf9b675 100644 --- a/lib/code_climate/test_reporter/formatter.rb +++ b/lib/code_climate/test_reporter/formatter.rb @@ -12,41 +12,27 @@ module CodeClimate module TestReporter class Formatter - def format(result) - return true unless CodeClimate::TestReporter.run? + class InvalidSimpleCovResultError < StandardError; end - print "Coverage = #{result.source_files.covered_percent.round(2)}%. " - - payload = to_payload(result) - PayloadValidator.validate(payload) - if write_to_file? - file_path = File.join(Dir.tmpdir, "codeclimate-test-coverage-#{SecureRandom.uuid}.json") - print "Coverage results saved to #{file_path}... " - File.open(file_path, "w") { |file| file.write(payload.to_json) } - else - client = Client.new - print "Sending report to #{client.host} for branch #{Git.branch_from_git_or_ci}... " - client.post_results(payload) + def format(results) + begin + validated_results = results.values.fetch(0).fetch("coverage") + rescue NoMethodError, KeyError => ex + raise InvalidSimpleCovResultError, ex.message end - puts "done." - true - rescue => ex - puts ExceptionMessage.new(ex).message - false - end + simplecov_results = SimpleCov::Result.new(validated_results) - # actually private ... - def short_filename(filename) - return filename unless ::SimpleCov.root - filename = filename.gsub(/^#{::SimpleCov.root}/, ".").gsub(%r{^\./}, "") - apply_prefix filename + payload = to_payload(simplecov_results) + PayloadValidator.validate(payload) + + payload end private def partial? - tddium? + CodeClimate::TestReporter.tddium? end def to_payload(result) @@ -62,7 +48,7 @@ def to_payload(result) end { - name: short_filename(file.filename), + name: ShortenFilename.new(file.filename).short_filename, blob_id: CalculateBlob.new(file.filename).blob_id, coverage: file.coverage.to_json, covered_percent: round(file.covered_percent, 2), @@ -91,34 +77,15 @@ def to_payload(result) simplecov_root: ::SimpleCov.root, gem_version: VERSION, }, - ci_service: ci_service_data, + ci_service: CodeClimate::TestReporter.ci_service_data, } end - def tddium? - ci_service_data && ci_service_data[:name] == "tddium" - end - # Convert to Float before rounding. # Fixes [#7] possible segmentation fault when calling #round on a Rational def round(numeric, precision) Float(numeric).round(precision) end - - def write_to_file? - warn "TO_FILE is deprecated, use CODECLIMATE_TO_FILE" if ENV["TO_FILE"] - tddium? || ENV["CODECLIMATE_TO_FILE"] || ENV["TO_FILE"] - end - - def apply_prefix(filename) - prefix = CodeClimate::TestReporter.configuration.path_prefix - return filename if prefix.nil? - "#{prefix}/#{filename}" - end - - def ci_service_data - @ci_service_data ||= Ci.service_data - end end end end diff --git a/lib/code_climate/test_reporter/post_results.rb b/lib/code_climate/test_reporter/post_results.rb new file mode 100644 index 0000000..8145686 --- /dev/null +++ b/lib/code_climate/test_reporter/post_results.rb @@ -0,0 +1,30 @@ +module CodeClimate + module TestReporter + class PostResults + def initialize(results) + @results = results + end + + def post + if write_to_file? + file_path = File.join(Dir.tmpdir, "codeclimate-test-coverage-#{SecureRandom.uuid}.json") + print "Coverage results saved to #{file_path}... " + File.open(file_path, "w") { |file| file.write(@results.to_json) } + else + client = Client.new + print "Sending report to #{client.host} for branch #{Git.branch_from_git_or_ci}... " + client.post_results(@results) + end + + puts "done." + end + + private + + def write_to_file? + warn "TO_FILE is deprecated, use CODECLIMATE_TO_FILE" if ENV["TO_FILE"] + CodeClimate::TestReporter.tddium? || ENV["CODECLIMATE_TO_FILE"] || ENV["TO_FILE"] + end + end + end +end diff --git a/lib/code_climate/test_reporter/shorten_filename.rb b/lib/code_climate/test_reporter/shorten_filename.rb new file mode 100644 index 0000000..61cb9b7 --- /dev/null +++ b/lib/code_climate/test_reporter/shorten_filename.rb @@ -0,0 +1,22 @@ +module CodeClimate + module TestReporter + class ShortenFilename + def initialize(filename) + @filename = filename + end + + def short_filename + return @filename unless ::SimpleCov.root + apply_prefix @filename.gsub(/^#{::SimpleCov.root}/, ".").gsub(%r{^\./}, "") + end + + private + + def apply_prefix(filename) + prefix = CodeClimate::TestReporter.configuration.path_prefix + return filename if prefix.nil? + "#{prefix}/#{filename}" + end + end + end +end diff --git a/lib/code_climate/test_reporter/version.rb b/lib/code_climate/test_reporter/version.rb index b239a33..2e4c7bd 100644 --- a/lib/code_climate/test_reporter/version.rb +++ b/lib/code_climate/test_reporter/version.rb @@ -1,5 +1,5 @@ module CodeClimate module TestReporter - VERSION = "0.6.0".freeze + VERSION = "1.0.0".freeze end end diff --git a/lib/codeclimate-test-reporter.rb b/lib/codeclimate-test-reporter.rb index 160efdf..85c1c1f 100644 --- a/lib/codeclimate-test-reporter.rb +++ b/lib/codeclimate-test-reporter.rb @@ -2,6 +2,8 @@ require "code_climate/test_reporter/calculate_blob" require "code_climate/test_reporter/version" require "code_climate/test_reporter/client" +require "code_climate/test_reporter/post_results" +require "code_climate/test_reporter/shorten_filename" require "code_climate/test_reporter/formatter" require "code_climate/test_reporter/configuration" require "code_climate/test_reporter/git" diff --git a/spec/fixtures/fake_project.tar.gz b/spec/fixtures/fake_project.tar.gz new file mode 100644 index 0000000..3c4cb72 Binary files /dev/null and b/spec/fixtures/fake_project.tar.gz differ diff --git a/spec/fixtures/test_file.rb b/spec/fixtures/test_file.rb new file mode 100644 index 0000000..84275f9 --- /dev/null +++ b/spec/fixtures/test_file.rb @@ -0,0 +1,4 @@ +line1 +line2 +line3 +line4 diff --git a/spec/lib/calculate_blob_spec.rb b/spec/lib/calculate_blob_spec.rb index 4cb75de..3c98371 100644 --- a/spec/lib/calculate_blob_spec.rb +++ b/spec/lib/calculate_blob_spec.rb @@ -16,8 +16,10 @@ module CodeClimate::TestReporter let(:fixture) { File.expand_path("../../fixtures/encoding_test_iso.rb", __FILE__) } it 'falls back to git' do - expect(File).to receive(:open).and_raise(EncodingError) - expect(subject.blob_id).to eq('eb82c22dadb9c47a7fed87211623f6856e112f46') + capture_io do + expect(File).to receive(:open).and_raise(EncodingError) + expect(subject.blob_id).to eq('eb82c22dadb9c47a7fed87211623f6856e112f46') + end end end diff --git a/spec/lib/formatter_spec.rb b/spec/lib/formatter_spec.rb index c5d13eb..bf93155 100644 --- a/spec/lib/formatter_spec.rb +++ b/spec/lib/formatter_spec.rb @@ -3,138 +3,63 @@ module CodeClimate::TestReporter describe Formatter do - let(:project_path) { "spec/tmp" } - let(:project_file) { "fake_project.rb" } let(:formatter) { Formatter.new } - let(:source_files) { - double( - :covered_percent => 24.3, - :covered_strength => 33.2, - ) - } - let(:files) { - [ - double( - :lines => [double, double, double], - :covered_lines => [double, double], - :missed_lines => [double], - :skipped_lines => [double(:line_number => 5), double(:line_number => 6)], - :filename => project_file, - :coverage => [0,3,2,nil,1,0], - :covered_percent => 33.2, - :covered_strength => 2 - ) - ] - } - - let(:simplecov_result) { - double( - :covered_percent => 24.3, - :covered_strength => 33.2, - :files => files, - :source_files => source_files, - :created_at => Time.at(1379704336), - :command_name => "rspec" - ) - } let(:expected_request) { { - "repo_token" => "172754c1bf9a3c698f7770b9fb648f1ebb214425120022d0b2ffc65b97dff531", - "source_files" => + repo_token: "172754c1bf9a3c698f7770b9fb648f1ebb214425120022d0b2ffc65b97dff531", + source_files: [ { - "name" => project_file, - "blob_id" => "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", - "coverage" => "[0,3,2,null,null,null]", - "covered_percent" => 33.2, - "covered_strength" => 2.0, - "line_counts" => {"total"=>3, "covered"=>2, "missed"=>1} + name: "spec/fixtures/fake_project/fake_project.rb", + blob_id: "84275f9939456e87efd6932bdf7fe01d52a53116", + coverage: "[5,3,null,0]", + covered_percent: 66.67, + covered_strength: 2.7, + line_counts: { total: 4, covered: 2, missed: 1} } ], - "run_at" => 1379704336, - "covered_percent" => 24.3, - "covered_strength" => 33.2, - "line_counts" => {"total" => 3, "covered" => 2, "missed" => 1 }, - "partial"=> false, - "git" => + run_at: Time.now.to_i, + covered_percent: 66.67, + covered_strength: 2.7, + line_counts: { total: 4, covered: 2, missed: 1 }, + partial: false, + git: { - "head" => @commit_sha, - "committed_at" => @committed_at.to_i, - "branch" => "master" + head: "7a36651c654c73e7e9a6dfc9f9fa78c5fe37241e", + committed_at: 1474318896, + branch: "master" }, - "environment" => + environment: { - "test_framework" => "rspec", - "pwd" => Dir.pwd, - "rails_root" => nil, - "simplecov_root" => Dir.pwd, - "gem_version" => VERSION + test_framework: "rspec", + pwd: Dir.pwd, + rails_root: nil, + simplecov_root: SimpleCov.root, + gem_version: VERSION }, - } + }.merge!(ci_service: CodeClimate::TestReporter.ci_service_data) } before do @old_pwd = Dir.pwd - FileUtils.mkdir_p(project_path) - FileUtils.cd(project_path) - FileUtils.touch(project_file) - SimpleCov.root(Dir.pwd) - system("git init") - system("git add #{project_file}") - system("git commit -m 'initial commit'") - @commit_sha = `git log -1 --pretty=format:'%H'` - @committed_at = `git log -1 --pretty=format:'%ct'` + FileUtils.cd("#{Dir.pwd}/spec/fixtures") + `tar -xvzf fake_project.tar.gz` + FileUtils.cd("fake_project") end after do + FileUtils.rm_rf("#{@old_pwd}/spec/fixtures/fake_project") FileUtils.cd(@old_pwd) - FileUtils.rm_rf(project_path) end - it "sends an http request with all the coverage information" do - allow(CodeClimate::TestReporter).to receive(:run?).and_return(true) - - stub = stub_request(:post, "http://cc.dev/test_reports"). - with(:headers => {'Content-Encoding'=>'gzip', 'Content-Type'=>'application/json', 'User-Agent'=>"Code Climate (Ruby Test Reporter v#{CodeClimate::TestReporter::VERSION})"}) - requests = capture_requests(stub) - - formatter.format(simplecov_result) - - uncompressed = inflate(requests.first.body) - expected_request.merge!("ci_service" => Ci.service_data) - expected_json = JSON.parse(expected_request.to_json, symbolize_names: true) - expect(JSON.parse(uncompressed, symbolize_names: true)).to eq(expected_json) - end - - describe '#short_filename' do - it 'should return the filename of the file relative to the SimpleCov root' do - expect(formatter.send(:short_filename, 'file1')).to eq('file1') - expect(formatter.send(:short_filename, "#{::SimpleCov.root}/file1")).to eq('file1') - end - - context "with path prefix" do - before do - CodeClimate::TestReporter.configure do |config| - config.path_prefix = 'custom' - end - end - - after do - CodeClimate::TestReporter.configure do |config| - config.path_prefix = nil - end - end - - it 'should include the path prefix if set' do - expect(formatter.send(:short_filename, 'file1')).to eq('custom/file1') - expect(formatter.send(:short_filename, "#{::SimpleCov.root}/file1")).to eq('custom/file1') - end - end - - it "should not strip the subdirectory if it has the same name as the root" do - expect(formatter.send(:short_filename, "#{::SimpleCov.root}/#{::SimpleCov.root}/file1")).to eq("#{::SimpleCov.root}/file1") - end + it "converts simplecov format to code climate http payload format" do + simplecov_result = { "RSpec" => + { "coverage" => + { "#{SimpleCov.root}/spec/fixtures/fake_project/fake_project.rb" => [5,3,nil,0] } + } + } + expect(formatter.format(simplecov_result)).to eq(expected_request) end end end diff --git a/spec/lib/shorten_filename_spec.rb b/spec/lib/shorten_filename_spec.rb new file mode 100644 index 0000000..70affd7 --- /dev/null +++ b/spec/lib/shorten_filename_spec.rb @@ -0,0 +1,40 @@ +require 'spec_helper' +require 'fileutils' + +module CodeClimate::TestReporter + describe ShortenFilename do + let(:shorten_filename){ ShortenFilename.new('file1') } + let(:shorten_filename_with_simplecov_root) { ShortenFilename.new("#{::SimpleCov.root}/file1") } + let(:shorten_filename_with_double_simplecov_root) { ShortenFilename.new("#{::SimpleCov.root}/#{::SimpleCov.root}/file1") } + + describe '#short_filename' do + it 'should return the filename of the file relative to the SimpleCov root' do + expect(shorten_filename.send(:short_filename)).to eq('file1') + expect(shorten_filename_with_simplecov_root.send(:short_filename)).to eq('file1') + end + + context "with path prefix" do + before do + CodeClimate::TestReporter.configure do |config| + config.path_prefix = 'custom' + end + end + + after do + CodeClimate::TestReporter.configure do |config| + config.path_prefix = nil + end + end + + it 'should include the path prefix if set' do + expect(shorten_filename.send(:short_filename)).to eq('custom/file1') + expect(shorten_filename_with_simplecov_root.send(:short_filename)).to eq('custom/file1') + end + end + + it "should not strip the subdirectory if it has the same name as the root" do + expect(shorten_filename_with_double_simplecov_root.send(:short_filename)).to eq("#{::SimpleCov.root}/file1") + end + end + end +end diff --git a/spec/lib/test_reporter_spec.rb b/spec/lib/test_reporter_spec.rb index c074861..09decbf 100644 --- a/spec/lib/test_reporter_spec.rb +++ b/spec/lib/test_reporter_spec.rb @@ -1,8 +1,13 @@ require 'spec_helper' describe CodeClimate::TestReporter do + let(:logger) { double.as_null_object } let(:reporter) { CodeClimate::TestReporter.dup } + before do + allow(CodeClimate::TestReporter.configuration).to receive(:logger).and_return(logger) + end + describe '.run_on_current_branch?' do it 'returns true if there is no branch configured' do allow(reporter).to receive(:configured_branch).and_return(nil) @@ -24,7 +29,7 @@ end it 'logs a message if false' do - expect_any_instance_of(Logger).to receive(:info) + expect(logger).to receive(:info) allow(reporter).to receive(:current_branch).and_return("another-branch") allow(reporter).to receive(:configured_branch).and_return(:master) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 7cd56db..e243727 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,6 @@ +require "simplecov" +SimpleCov.start + require 'bundler/setup' require 'pry' require 'codeclimate-test-reporter' @@ -17,6 +20,20 @@ def capture_requests(stub) stub.to_return { |r| requests << r; {body: "hello"} } requests end + + def capture_io + stdout = $stdout + stderr = $stderr + $stdout = StringIO.new + $stderr = StringIO.new + + yield if block_given? + + [$stdout, $stderr] + ensure + $stdout = stdout + $stderr = stderr + end end RSpec.configure do |c|