在一堆RSPEC Rails单元规格中,我会做类似的事情:

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() 用于插入DSL代码,例如RSPEC 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示例的等效是什么?

有帮助吗?

解决方案

好的,这花了一些搞砸了,但是我想我可以正常工作。这是一些元编程的黑客,我个人只会使用您描述的第一件事,但这是您想要的: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? 方法,但两种测试都进行,因此应该有效。

您可以定义(并重命名)您的extplemacros模块 spec_helper.rb 文件,它将用于包含。你想打电话 include ExampleMacros 在你的 describe 块(而不是其他块)。

要使所有规格都包括自动包含模块,请像这样配置RSPEC:

# RSpec 2.0.0
RSpec.configure do |c|
  c.include ExampleMacros
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top