Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/chefspec/coverage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def report!
report = {}.tap do |h|
h[:total] = @collection.size
h[:touched] = @collection.count { |_, resource| resource.touched? }
h[:coverage] = ((h[:touched] / h[:total].to_f) * 100).round(2)
h[:coverage] = coverage_percentage(h[:touched], h[:total])
end

report[:untouched_resources] = @collection.collect do |_, resource|
Expand All @@ -179,6 +179,18 @@ def report!

private

#
# The percentage of covered resources, guarding against a division by zero
# when no resources were collected (which would otherwise produce NaN).
#
# @return [Float]
#
def coverage_percentage(touched, total)
return 0.0 if total == 0

((touched / total.to_f) * 100).round(2)
end

def find(resource)
@collection[resource.to_s]
end
Expand Down
21 changes: 21 additions & 0 deletions spec/unit/coverage_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require "spec_helper"

describe ChefSpec::Coverage do
subject(:coverage) { described_class.instance }

describe "#coverage_percentage" do
it "returns 0.0 when there are no resources instead of NaN" do
result = coverage.send(:coverage_percentage, 0, 0)
expect(result).to eq(0.0)
expect(result).not_to be_nan
end

it "calculates the touched percentage" do
expect(coverage.send(:coverage_percentage, 3, 4)).to eq(75.0)
end

it "rounds to two decimal places" do
expect(coverage.send(:coverage_percentage, 1, 3)).to eq(33.33)
end
end
end
Loading