Help us understand the problem. What is going on with this article?

Ruby の coverage を使ってメソッドが呼ばれた回数を調べる

More than 1 year has passed since last update.

Ruby 2.5 の coverage では メソッドカバレッジを取得出来るようになったので、メソッドの呼ばれた回数を調べるコードを書いてみました。

チェック用のサンプルコード

fizzbuzz.rb
def fizz
  "Fizz"
end

def buzz
  "Buzz"
end

def fizzbuzz
  "FizzBuzz"
end

1.upto(100) do |n|
  if n % 15 == 0
    puts fizzbuzz
  elsif n % 3 == 0
    puts fizz
  elsif n % 5 == 0
    puts buzz
  else
    puts n
  end
end

確認用のコード (RUBY_VERSION >= "2.5.0")
結果を見やすくするために termianl-table を使用しています

method_call_count.rb
require "coverage"
require "terminal-table"

Coverage.start(methods: true)
require_relative "fizzbuzz"
result = Coverage.result

rows = []

result.each do |filepath, coverage_data|
  filename = File.basename(filepath)
  methods = coverage_data[:methods]

  methods.each do |method_data, count|
    next if count.zero?

    defined_class, method_id, _from_row, _from_col, _to_row, _to_col = *method_data
    rows << [filename, defined_class, method_id, count]
  end
end

header = %w(filename defined_class method_id count)
rows.sort_by! { |e| -e.last }
table = Terminal::Table.new headings: header, rows: rows
puts table

実行結果

.
.
# fizzbuzz.rb の結果が流れる
.
.
+-------------+---------------+-----------+-------+
| filename    | defined_class | method_id | count |
+-------------+---------------+-----------+-------+
| fizzbuzz.rb | Object        | fizz      | 27    |
| fizzbuzz.rb | Object        | buzz      | 14    |
| fizzbuzz.rb | Object        | fizzbuzz  | 6     |
+-------------+---------------+-----------+-------+

こんな感じで取得することが出来ました

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした