0

speclog = Logger.new('log/rspec.log')rspec 統合テストの 1 つにカスタム ロガーがあり、 before(:each) ... endandit ... endブロック内から呼び出すと正常に動作します。

ただし、共通の「すべてを表示」ルーチンを独自のメソッドに移動していくつかのテストを DRY すると、そのメソッドで 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) describe ブロック内で 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 に答える