There's an echo in my head

日々のメモ。

RSpecにdescribeやcontextで使えるメソッドを実装する

describecontext間で共通する処理をメソッドにするとスッキリするんだけど、それをspecファイルをまたいで共有したいときに。

module RSpec
  module Core
    module MyHelper # 適当に名付ける
      module ExampleGroupMethods
        def my_let(*args)
          p args
          let(*args)
        end
      end
      def self.included(mod)
        mod.extend ExampleGroupMethods
      end
    end
  end
end

RSpec::Core::ExampleGroup.class_eval do
  include RSpec::Core::MyHelper
end

こうするとExampleGroupMethodsに定義されたメソッドがdescribecontextのなかで使えるようになる。上の例のように自作のメソッド内でletを呼び出すようなこともできる。

require "/path/to/above"
describe Foo do
  my_let(:bar) { "bar" }
end

RSpec::Core::Letあたりがシンプルでわかりやすいかと思う。

このブログに出てくるコードスニペッツは、引用あるいは断りがない限りMITライセンスです。