【问题标题】:Rspec log sql to console for filtered / tagged specsRspec 将 sql 记录到控制台以获取过滤/标记的规范
【发布时间】:2014-12-19 00:57:29
【问题描述】:

如果我专门标记规范,或者至少仅针对重点示例,我希望能够在控制台中看到 SQL 输出。我总是可以通过添加来显示它:

ActiveRecord::Base.logger = Logger.new(STDOUT)

但它是冗长的。我试图使用这样的环绕条件但没有成功:

# log SQL to console for tests tagged with :db
config.around do |example|
  if example.metadata[:db]
    ActiveRecord::Base.logger = Logger.new(STDOUT)
  end
end

如何实现?

【问题讨论】:

  • 你还没有恢复到旧的记录器

标签: ruby-on-rails ruby postgresql rspec filtering


【解决方案1】:

我必须在我的spec_helper.rb 中使用beforeafter

# log SQL to console for tests tagged with :db
config.before(:each, db: true) do
  @default_logger = ActiveRecord::Base.logger
  ActiveRecord::Base.logger = Logger.new(STDOUT)
end

# log SQL to console for tests tagged with :db
config.after(:each, db: true) do
  ActiveRecord::Base.logger = @default_logger
end

我喜欢 Paul N. 建议的“确保”可能性并摆脱实例变量的想法。 Paul N. 的方法会引发语法错误,因为 ensure 子句只能在方法内运行。

def with_std_out_logger
  default_logger = ActiveRecord::Base.logger
  ActiveRecord::Base.logger = Logger.new(STDOUT)
  yield
ensure
  ActiveRecord::Base.logger = default_logger
end

config.around(:each, db: true) do |example|
  with_std_out_logger { example.run }
end

【讨论】:

  • 太棒了!我正在根据 Paul N. 的建议使用您的第二种解决方案。谢谢你们!
【解决方案2】:
RSpec.configure do |config|
  config.around(:example, db: true) do |example|
    old_logger = ActiveRecord::Base.logger
    ActiveRecord::Base.logger = Logger.new(STDOUT)

    example.run

  ensure
     ActiveRecord::Base.logger = old_logger
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多