2016-05-18 9 views
2

私はRubyの単体テストには新しく、STDOUTをチェックする仕様を作成するのにいくつか問題があります。私はテストしているコードがクラス/メソッド内にある場合にSTDOUTをテストする方法を知っていますが、クラスまたはメソッド内にない通常のRubyファイルから来るputsステートメントをテストしたいだけです。RSpecのSTDOUTの取得

Failures: 

    1) Something I'm Testing should print Welcome to the Book Club! 
    Failure/Error: expect {$stdout}.to output("Welcome to the Book Club!\n").to_stdout 

     expected block to output "Welcome to the Book Club!\n" to stdout, but output nothing 
     Diff: 
     @@ -1,2 +1 @@ 
     -Welcome to the Book Club! 
     # ./spec/my_spec.rb:9:in `block (2 levels) in <top (required)>' 

Finished in 0.01663 seconds (files took 0.08195 seconds to load) 
1 example, 1 failure 

Failed examples: 

rspec ./spec/my_spec.rb:7 # Something I'm Testing should print Welcome to the Book Club! 
:ここ

my_file.rb

puts "Welcome to the Book Club!" 

から簡単な1つのライナーはここで私は、次のエラーメッセージが表示されます仕様

my_spec.rb

require_relative 'my_file.rb' 

    describe "Something I'm Testing" do 
    it 'should print Welcome to the Book Club!' do 

     expect {$stdout}.to output("Welcome to the Book Club!\n").to_stdout 

     end 
    end 

だです

を使用してmy_file.rbからSTDOUTをキャプチャすることはできますが、それは機能しません。出力は何も言わないままです。私は出力をキャプチャすることについて話すこの記事を見つけましたStringIOTesting STDOUT output in Rspec

しかし、その方法は私のためには機能しませんでした。私は間違って何をしていますか?

ありがとうございます!

答えて

5

putsメソッドは、テストが実行される前に一番上にmy_file.rbを含めると呼び出されます。あなたのテストの中にそれを含めてください。

describe "Something I'm Testing" do 
    it 'should print Welcome to the Book Club!' do 
    expect { require_relative 'my_file.rb' }.to output("Welcome to the Book Club!\n").to_stdout 
    end 
end 
+0

ありがとう!魅力のように働いた。次回は心に留めておきます。 – SalceCodec

+1

@Uzbekjonがあなたの質問に答えた場合は、チェックアイコンをクリックして回答を受け入れてください。詳細については、http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-workを参照してください。 –

関連する問題