Do you know of a way to find out which spec executed a line of code

I’ve opened a PR suggestion with simplecov - PR suggestion- show which spec executed a code. · Issue #1031 · simplecov-ruby/simplecov · GitHub but decided to post the question also here if anyone has found a solution

simple cov shows the number of time a code was executed, but not which spec was responsible for executing this code. I could not find this as a feature and I thought it will be interesting for us to implement it.

You click on the “Number of times the line was executed” and you see a table of the specs that were running when the line was touched, possibly even the stack trace.

What this will allow us is to quickly see which specs are testing a certain method.

In our new project there are a lot of specs both system and model and some of the code is tested through system specs but because system specs test a lot of things and test a feature on a high level it is difficult to quickly understand which system spec tested what.

This also allows us to identify cases where we are overtesting. Probably a few system specs are doing similar things and we can easily get rid of them and reduce the number of specs we have to support and also the execution time of the specs.

Have you tried to achieve this?

1 Like

I’ve only used this little bit of code placed in spec_helper.rb that figures out the origin:

def in_trace
  results = []
  (trace = { |tp| results << [tp.path, tp.lineno, tp.method_id, tp.event] }).enable

Then in an it block you can do this:

it 'should do cool stuff' do
  my_trace = in_trace do
    User.mark_as_active # Some method you care about
  # Show the line and method name
  puts "#{my_trace.first[0]}:#{my_trace.first[1]} (in #{my_trace.first[2]}"

You could go further through my_trace to find more detail about what was called, and perhaps further look up line ranges for each method by using source_location.

Hope this helps!

1 Like