如何从我的RSpec测试中删除路由/控制器日志?

时间:2015-11-09 10:09:29

标签: ruby-on-rails rspec

当我运行RSpec时,我有一些我想要摆脱的不需要的控制器/路由日志。

我如何摆脱那些?

rspec
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}

Randomized with seed 61970
....Processing by Api::CommentsController#update as HTML
  Parameters: {"comment"=>{"content"=>"Attempt to edit comment."}, "id"=>"28"}
Filter chain halted as :find_comment rendered or redirected
Completed 401 Unauthorized in 20ms (ActiveRecord: 4.4ms)
.Processing by Api::CommentsController#update as HTML
  Parameters: {"comment"=>{"content"=>"Editing is nice"}, "id"=>"29"}
Completed 200 OK in 22ms (Views: 0.6ms | ActiveRecord: 5.3ms)
.Processing by Api::CommentsController#update as HTML
  Parameters: {"comment"=>{"content"=>"Attempt to edit someone else's comment."}, "id"=>"30"}
Filter chain halted as :find_comment rendered or redirected
Completed 401 Unauthorized in 14ms (ActiveRecord: 3.3ms)
.Processing by Api::CommentsController#create as HTML
  Parameters: {"comment"=>{"subject_id"=>"201", "subject_type"=>"Card", "content"=>"This is so useful!"}}
Completed 200 OK in 41ms (Views: 0.6ms | ActiveRecord: 9.2ms)

1 个答案:

答案 0 :(得分:1)

1.你可以写一个这样的过滤器:

def silence_action
  Rails.logger.silence do
    yield
  end
end

在rspec上添加以下行,以便记录器静音:

RSpec.describe BaseController, :type => :controller do
  controller.class.around_filter :silence_action, :only => :action
end

2.另一种使记录器静音的方法是编写自定义记录器:

# lib/custom_logger.rb
 class CustomLogger < Rails::Rack::Logger
   def initialize  app, opts = {}
    @app = app
    @opts = opts
    @opts[:silenced] ||= []
  end

  def call  env
    if @opts[:silenced].include?(env['PATH_INFO']) || @opts[:silenced].any? {|silencer| silencer.is_a?( Regexp) && silencer.match( env['PATH_INFO']) }
      Rails.logger.silence do
        @app.call env
      end
    else
      super env
    end                        
  end
    end

然后在你的rspec你可以调用一个负责切换记录器的函数:

require File.dirname(__FILE__) + '/../lib/custom_logger.rb'

  def use_custom_logger
    Rails.application do
      config.middleware.swap Rails::Rack::Logger, CustomLogger, :silenced => ["/noisy/action.json"]
    end
  end