在一堆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()这样的助手方法来插入像rspec的it()方法那样的dsl代码呢?如果是普通的实例方法,我会这样做:
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?方法,但是两个测试都运行,所以应该可以工作。
您可以在spec_helper.rb文件中定义(并重命名)examplemacros模块,它将可用于包含。您想在您的include ExampleMacros块中调用describe(而不是其他块)。
要使所有规范自动包含模块,请按如下方式配置rspec:
# RSpec 2.0.0
RSpec.configure do |c|
  c.include ExampleMacros
end

关于ruby - 如何编写插入rspec示例的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3974331/

10-15 00:43