In a bunch of rspec rails unit specifications I do something like:
describe Foo do
[:bar, :baz].each do |a|
it "should have many #{a}" do
Foo.should have_many(a)
end
end
end
For cleaner code I’d rather do something like:
describe Foo do
spec_has_many Foo, :bar, :baz
end
So how do I write a helper method like spec_has_many() for inserting DSL code like rspec’s it() method? If it were for an ordinary instance method I’d do something like:
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
What would be the equivalent for defining rspec examples?
Ok, this took some messing around, but I think I got it working. It’s a bit of metaprogramming hackery, and I personally would just use the first thing you described, but it’s what you wanted 😛
My specs fail because Foo doesn’t have a
has_many?method, but both tests run, so it should work.You can define (and rename) the ExampleMacros module in your
spec_helper.rbfile and it will be available for inclusion. You want to callinclude ExampleMacrosin yourdescribeblocks (and not any others).To make all of your specs include the module automatically, configure RSpec like so: