[rspec-users] how do I mock the Rails Logger with should_receive?

Mikel Lindsaar raasdnil at gmail.com
Wed Jun 25 02:55:57 EDT 2008

On Fri, Jun 13, 2008 at 8:56 AM, john <eagerwombat at gmail.com> wrote:
> I'm trying to mock the Rails Logger for the following code:
>     rescue TimeoutError => error
>       $logger.error("#{self.name} Timeout for #{path}: #{error}") and return
>     rescue SocketError => error
>       $logger.error("#{self.name} SocketError for #{path}: #{error}") and
> return
>     rescue StandardError => error
>       $logger.error("#{self.name} Error for #{path}: #{error}") and return
>     end
> my failed attempt to spec:
>    logger = mock_model(Logger)
>    logger.stub(:error)
>    logger.should_receive(:error).with(:any_args)
> Do you know of any solution for mocking this?

The problem you are hitting is that the 'logger' you are accessing
from within your code is different depending on what and where you are
accessing it from.  Assuming you are in a Rails Model, then the
'logger' is actually hooked into the model itself, so stubbing it
would be like:

class Person < ActiveRecord::Base
  def log_Test

it "should talk to the logger" do

> Also, do you think the Rails Logger is worth mocking?

Well, that depends.  Is logging the data a part of your application
that you need to know works?  If you are doing transaction processing,
the you probably do want to ensure that your logger is tracing these
transactions as part of an audit trail.

It's up to your problem domain.


More information about the rspec-users mailing list