【发布时间】:2012-06-02 09:48:12
【问题描述】:
我正在努力保持我的规范干净和干燥,但我对一个 API 进行了一些测试,除了正在测试哪个版本的 API 之外,它们是相同的。我可以简单地使用这样的东西来重复规范:
%w( v1 v2 ).each do |version|
describe "Query #{version} API" do
it "responds with JSON"
# make the call using the version
end
end
end
但我想要一些更干净的东西,所以我写了这个方法:
module RepetitivelyDescribe
def repetitively_describe(*args, &example_group_block)
options = args.extract_options!
options.delete(:for).each do |item|
item_args = args.collect(&:dup) + [options.dup]
item_args[0] << " [#{item}]"
describe(*item_args) do
example_group_block.call item
end
end
end
end
RSpec::Core::ExampleGroup.extend RepetitivelyDescribe
然后我的测试可能看起来更像这样:
repetitively_describe "Query API", :for => %( v1 v2 ) do |version|
it "responds with JSON"
# make the call using the version
end
end
我意识到这有点学究气,但缩进少了一级,如果我要经常打这个电话,我希望它更干净。
当然,它并没有像我想要的那样工作。我的repetitively_describe 中对describe 的调用不会记录到RSpec 输出(使用文档格式输出时),尽管其中的示例确实会重复并按预期使用版本块参数。本质上,该级别的上下文丢失了(repetitively_describe 块外部和内部的describe 块被保留)。
如果需要,a gist 中有更详细的示例代码。关于为什么这不能正常工作的任何线索?
【问题讨论】:
-
我个人会为此使用共享上下文或共享示例组。
it_behaves_like "a query API" do let(:version) { :v1 } end。 relishapp.com/rspec/rspec-core/docs/example-groups/…relishapp.com/rspec/rspec-core/v/2-9/docs/example-groups/…
标签: ruby rspec metaprogramming