如果我专门标记规范,或者至少仅针对重点示例,我希望能够在我的控制台中看到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
如何实现?
答案 0 :(得分:1)
我必须在before
after
和spec_helper.rb
# 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
我喜欢保罗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
答案 1 :(得分:1)
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