[英]Rspec log sql to console for filtered / tagged specs
I would like to be able to see the SQL output in my console if I tag a spec specifically, or at least only for focused examples. 如果我专门标记一个规范,或者至少仅针对重点示例,我希望能够在控制台中看到SQL输出。 I'm able to always show it by adding:
我总是可以通过添加以下内容来显示它:
ActiveRecord::Base.logger = Logger.new(STDOUT)
but it's to verbose. 但这很冗长。 I was trying to use an around condition like this with no success:
我试图使用这样的条件,但没有成功:
# 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
How can it be achieved? 如何实现?
I had to use before
and after
in my spec_helper.rb
我必须在
spec_helper.rb
使用before
和after
# 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
I liked the idea of having the "ensure" possibility suggested from Paul N. and get rid of the instance variable. 我喜欢Paul N.建议的“确保”可能性的想法,并且摆脱了实例变量。 Paul N.'s approach raises syntax errors as the
ensure
clause can only be run inside a method. 保罗·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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.