7

たくさんのrspecrailsユニットの仕様で、私は次のようなことをします。

describe Foo do
  [:bar, :baz].each do |a|
    it "should have many #{a}" do
      Foo.should have_many(a)
    end
  end
end

よりクリーンなコードのために、私はむしろ次のようなことをしたいと思います:

describe Foo do
  spec_has_many Foo, :bar, :baz
end

spec_has_many()では、rspecのメソッドのようなDSLコードを挿入するようなヘルパーメソッドをどのように書くのit()ですか?通常のインスタンスメソッドの場合、次のようにします。

def spec_has_many(model, *args)
  args.each do |a|
    define_method("it_should_have_many_#{a}") do
      model.should have_many(a)
    end
  end
end

rspecの例を定義するのに相当するものは何ですか?

4

1 に答える 1

9

わかりました、これには少しいじりましたが、うまくいったと思います。これはちょっとしたメタプログラミングのハッカーです。個人的には、あなたが最初に説明したものを使用しますが、それはあなたが望んでいたものです:P

module ExampleMacros
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    # This will be available as a "Class Macro" in the included class
    def should_have_many(*args)
      args.each do |a|
        # Runs the 'it' block in the context of the current instance
        instance_eval do
          # This is just normal RSpec code at this point
          it "should have_many #{a.to_s}" do
            subject.should have_many(a)
          end
        end
      end
    end
  end
end

describe Foo do
  # Include the module which will define the should_have_many method
  # Can be done automatically in RSpec configuration (see below)
  include ExampleMacros

  # This may or may not be required, but the should_have_many method expects
  # subject to be defined (which it is by default, but this just makes sure
  # it's what we expect)
  subject { Foo }

  # And off we go. Note that you don't need to pass it a model
  should_have_many :a, :b
end

Foo にはメソッドがないため、私の仕様は失敗しhas_many?ますが、両方のテストが実行されるため、動作するはずです。

ファイルで ExampleMacros モジュールを定義 (および名前変更) するとspec_helper.rb、含めることができるようになります。include ExampleMacros自分のブロックを呼び出したいdescribe(他のブロックは呼び出したくない)。

すべての仕様にモジュールが自動的に含まれるようにするには、次のように RSpec を構成します。

# RSpec 2.0.0
RSpec.configure do |c|
  c.include ExampleMacros
end
于 2010-10-20T03:20:43.220 に答える