2012年6月5日火曜日

モジュールのテスト

RSpecでモジュールをテストする方法です。
いくつか方法があると思いますがここでは3つ挙げます。

まず一つ目はRSpec.configureでincludeする方法。

lib/app.rb

module Hello
  module World
    def say
      "Hello World!"
    end
  end
end

spec/spec_helper.rb

require 'app'

RSpec.configure do |config|
  config.include Hello::World
end

spec/app_spec.rb

require 'spec_helper'

describe "Hello::World" do
  context "#say" do
    context "with including Module via RSpec.configure" do
      it { say.should == "Hello World!" }
    end
  end
end

2つ目はdescribeブロックでincludeする方法。こちらはspc_helper.rbのRSpec.configure記述が不要です。

spec/app_spec.rb

require 'spec_helper'

describe "Hello::World" do
  include Hello::World
  context "#say" do
    context "with including Module within the 'describe' block" do
      it { say.should == "Hello World!" }
    end
  end
end
これらはsinatraでRack::TESTを使用する方法と同様です。

別の方法としてオブジェクト拡張を使う方法があります。オブジェクト拡張についてはメタプログラミングRubyに記述があります。

spec/app_spec.rb

require 'spec_helper'

describe "Hello::World" do
  context "with anonymous inner class" do
    subject do
      obj = Object.new
      obj.extend Hello::World
      obj
    end
    its(:say) { should == "Hello World!" }
  end
end

1、2番目はRack::Testの他にもhelperのテストでも同様に使用できるでしょう。特定のクラスで使用することを想定してテストしたい場合や、局所的に記述したい時は3番目で書くとよいのではないでしょうか。

0 件のコメント:

コメントを投稿