好的,这花了一些时间,但我想我得到了它的工作。这有点像元编程黑客,我个人只会使用你描述的第一件事,但这就是你想要的: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