0

我在我的一个 rspec 集成测试中有一个自定义记录器,当我从and块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 ?如果是这样,为什么?

4

1 回答 1

0

解决方案是(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
于 2012-10-03T19:34:38.617 回答