Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access `expected` line from metadata

I want output line, which was failed during rspec comparasion inside example, but I don't know how to do it best. For example I have test like this:

require 'rspec'

describe 'My behaviour' do
  it 'should do something' do
    test_string = 'test'
    expect(test_string).to eq('failed_test')
  end

  after :each do |example|
    puts example.metadata[:expect_line]
  end
end

And I want to outputed line in after :each be

"expect(test_string).to eq('failed_test')"

I know, I have acces to example.metadata[:location] which return something like "./spec/test_spec.rb:4" and I can parse it and extract line, but is there already something like I need hided in whole example structure?

Update: I just understand. that example.metadata[:location] return not failed line, but actually line in whitch it started, so it have no use for me :( So question still exist - how to get failed line?

like image 254
ShockwaveNN Avatar asked Mar 04 '26 18:03

ShockwaveNN


1 Answers

This information isn't hidden anywhere in the example structure that I'm aware of. RSpec's default output shows the line that failed:

Failures:

  1) My Description should fail
     Failure/Error: expect(1).to eq(2)

       expected: 2
            got: 1

If we look at how rspec itself gets this in rspec/core/formatters/exception_presenter.rb and rspec/core/formatters/snippet_extractor.rb, it appears that they go through the backtrace of the example exception to find the spec file and extract the line (similar to what you mentioned). If there was an easier way to pull that out of the example, I would think RSpec itself would use that :)

like image 178
Andrew Schlei Avatar answered Mar 06 '26 06:03

Andrew Schlei