How do I get logging with rspec?

Say I’m testing a controller with rspec, and I have logger.debug and
logger.error calls.

Normally I’d like them to write to the appropriate file, but in this
case I’d like to see the output on STDOUT.

Is there an easy way to redirect logging in rspec to do this?

I’m thinking that

controller.should_receive(:logger).and_return(logger)

should start it off, but then how do I get the new logger to do puts
without defining a new class? I’m assuming there must be a “Ruby way”
to do it.

Will.

On 1/30/08, Will S. [email protected] wrote:

controller.should_receive(:logger).and_return(logger)

should start it off, but then how do I get the new logger to do puts
without defining a new class? I’m assuming there must be a “Ruby way”
to do it.

I’d think that
controller.should_receive!(:logger).and_return(Logger.new(STDOUT))
should do it.

Not sure whether or not you really want to use stub! vs.
should_receive here, do you really want to require that logger be
called or just allow it?

Also if you want to set expectations on what’s actually logged you
might want to do

@log_stream = StringIO.new
controller.stub!(:logger) and_return(Logger.new(@logstream))

and then get at the log output via something like @log_stream.string

Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Not sure whether or not you really want to use stub! vs.
should_receive here, do you really want to require that logger be
called or just allow it?

Good question. I think there are cases where I might want either or
both, depending on whether it’s for debugging or for support purposes.

Also if you want to set expectations on what’s actually logged you
might want to do

@log_stream = StringIO.new
controller.stub!(:logger) and_return(Logger.new(@logstream))
and then get at the log output via something like @log_stream.string

Great – that’s exactly what I need. Thank you.

Will.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs