Rspec cannot check log information output

I have a ruby-free ruby ​​application that uses logger to process log output in stdout.
I want to add specifications to verify this conclusion and found two ways to implement this and it seems that both methods do not work.

Thus, both methods are in this spec.rb file:

require 'rspec' 
require 'logger'

describe 'Logger' do   
  it 'expect to output' do
    expect { Logger.new(STDOUT).info('Hello') }.to output.to_stdout    
  end

  it 'expect to recieve' do
    expect(Logger.new(STDOUT).info('Hello')).to receive(:info)   
  end 
end

I have a terminal output with log messages, but both checks failed

+4
source share
2 answers

Usually I just use such doubles:

describe 'logging' do
  it 'handles output' do
    logger = double('logger')
    allow(Logger).to receive(:new).and_return(logger)

    run_some_code
    expect(logger).to receive(:info).with("Hello")
  end
end
+2
source

Replace STDOUTwith $stdout. It works:

expect { Logger.new($stdout).info('Hello') }.to output.to_stdout

, Rspec $stdout StringIO. , STDOUT $stdout.

, , . logger , :

logger = Logger.new($stdout)
expect { logger.info('Hello') }.to output.to_stdout # This won't work

:

expect(Logger.new(STDOUT).info('Hello')).to receive(:info)   

Rspec. - :

logger = Logger.new(STDOUT)
expect(logger).to receive(:info)   
logger.info("Hello")
0

Source: https://habr.com/ru/post/1660513/


All Articles