LoginSignup
7
7

More than 5 years have passed since last update.

fluentdプラグインのテストをrspecで書く

Last updated at Posted at 2014-12-10

fluentdプラグインのテストは基本的にtest-unitを使うことが前提になっていますが、一応、rspecを使うこともできます。
しかし普通にrspecを実行すると、test-unitの実行結果も表示されていまいます。

$ bundle exec rspec spec/out_lambda_spec.rb
...

Finished in 2.14 seconds (files took 0.2635 seconds to load)
3 examples, 0 failures
Run options:

# Running tests: # ↓末尾にtest-unitの出力が…

Finished tests in 0.013681s, 0.0000 tests/s, 0.0000 assertions/s.
0 tests, 0 assertions, 0 failures, 0 errors, 0 skips

また、rakeからrspecを実行すると--petternが不正なオプションとなってエラーになってしまいます。

$ bundle exec rake
../ruby -I.. rspec --pattern spec/\*\*\{,/\*/\*\*\}/\*_spec.rb
...

Finished in 2.05 seconds (files took 0.24343 seconds to load)
3 examples, 0 failures
../test/unit.rb:49:in `process_args': invalid option: --pattern (OptionParser::InvalidOption)
    from ../minitest/unit.rb:1042:in `_run'
    ...

しかし、rspecに慣れた身としてはできればrspecを使いたい、なんとか方法はないものか…といろいろ試行錯誤したところ、一応、普通に使えるようになったので、その方法を紹介したいと思います。

おまじない

結論から書くと、以下のコードをspec_helper.rbなどに書いておくと、rspecを実行しても余計な情報を出力されたり、エラーになったりすることがなくなります。

require 'fluent/test'
require 'fluent/plugin/out_...'

# Disable Test::Unit
module Test::Unit::RunCount; def run(*); end; end

RSpec.configure do |config|
  config.before(:all) do
    Fluent::Test.setup
  end
end

やっていること

なにをやっているのかだいたい分かると思いますが、一応解説します。

まずfluent/testをrequireするとtest/unit.rbがrequireされます

require 'test/unit'
require 'fluent/load'
require 'fluent/test/base'
...

test/unit.rbの末尾ではTest::Unit::Runner.autorunが実行されます

...
  end
end

Test::Unit::Runner.autorun

さらにTest::Unit::Runner.autorunの中ではat_exitでTest::Unit::Runner#runを実行しています

def self.autorun
  at_exit {
    Test::Unit::RunCount.run_once {
      exit(Test::Unit::Runner.new.run(ARGV) || true)
    } unless @@stop_auto_run
  } unless @@installed_at_exit
  @@installed_at_exit = true
end

ということでTest::Unit::Runner#runを上書きしてやれば、test-unitは実行されなくなります。

まとめ

あまり行儀のいいやり方ではないですが、一応rspecが普通に使えるようになるので、どーしてもrspecが使いたいという方は試してみると良いのではないでしょうか。

7
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7