我认为简单的'scope'问题:在 rails rspec 测试中,如何在 'it ...' 块之外的 DRY 方法中访问我的自定义记录器?



我在我的一个 rspec 集成测试中speclog = Logger.new('log/rspec.log')了一个自定义记录器,当我从 before(:each) ... endit ... end 块内部调用它时,它工作正常。

但是,当我通过将一个常见的"显示所有内容"例程移动到它自己的方法来干掉一些测试时,在该方法中调用 speclog 会抛出错误undefined local variable or method 'speclog'

#testit_spec.rb
require 'integration_spec_helper' 
speclog = Logger.new('log/rspec.log')
describe FooController do
  before(:each) do ... end 
  it "test1" do ... end # speclog directly inside here works fine
  it "test2" do ... end # but calling log_it_all throws error
  def log_it_all
    speclog.debug "common messages" #  SPECLOG is 'undefined' HERE?
  end
end

当我以上述常用方法访问speclog时,我是否需要在它前面加上,我不知道,Rspec::Something?如果是这样,为什么?

解决方案是 (a) 在描述块内声明 speclog 变量,以及 (b) 将其作为实例变量执行,例如 @speclog

#testit_spec.rb
require 'integration_spec_helper' 
describe FooController do
  @speclog = Logger.new('log/rspec.log')
  before(:each) do ... end 
  it "test1" do ... end # @speclog directly is ok
  it "test2" do ... end # and, calling log_it_all is ok
  def log_it_all
    @speclog.debug "common messages" #  SPECLOG is 'undefined' HERE?
  end
end

相关内容

最新更新