RSpecを使ってみて早速躓いた

Ruby on Rails 3.1.10で初めてRSpecを使おうとしてハマったのでメモ。

アプリ内でユーティリティ的に使う自作のクラスMyClassを作って

class MyClass
  def test_method
    return true
  end
end

それのtest_methodの戻り値がtrueであることをテストするために、このような./app/helpers/my_class_spec.rbを書いてみた。

require 'spec_helper'

describe MyClass do
  describe 'MyClassの' do
    before do
      @mine = MyClass.new
    end

    describe 'test_methodの' do
      it '戻り値がtrue' do
        @mine.test_method.should be_true
      end
    end
  end
end

それをrake specで実行すると、何やらスタックトレースとともにこのようなエラーを吐いて落ちた。

rspec ./spec/helpers/abusive_words_modifier_spec.rb:14 # MyClass MyClassの test_methodの 戻り値がtrue

Randomized with seed 46906

/Users/annymsprsn/.rbenv/versions/1.9.3-p392
  /lib/ruby/gems/1.9.1/gems/actionpack-3.1.10/lib
  /abstract_controller/helpers.rb:153:in `include':
  wrong argument type Class (expected Module) (TypeError)
(以下にスタックトレースが続く)

色々と調べた結果、このspecファイルの最上位のdescribeには、テスト対象のクラスではなくHelperを指定しなければならないらしい。とりあえずApplicationHelper(中身はほぼ空)を指定して

require 'spec_helper'

describe ApplicationHelper do
  describe 'MyClassの' do
  (中略)
  end
end

再度rake specを実行したらちゃんとテストが実行された。多分基本的なことが分かってない気がする…(今日になって初めて使ったので)。