一种选择是将允许的上传格式添加到您的控制器,并让测试内省您的控制器。这可能会使生产和测试代码都干涸。
class ApplicationController
def self.upload_formats
[:yaml, :json, :csv]
end
end
class OtherController < ApplicationController
def self.upload_formats
[:yaml, :json]
end
end
shared_examples 'it accepts uploads' do
let(:formats) { described_class.upload_formats }
...
end
这可能太干了;如果self.upload_formats 缺少格式,测试将无法捕捉到它。
您可以在共享示例中添加一个标志并传递它应该检查的格式。如果每种格式的测试都相似,这就变成了一个简单的循环。
shared_examples 'it accepts uploads' do |formats: [:yaml, :json, :csv]|
formats.each do |format|
let(:format) { format }
context "in #{format}" do
...
end
end
end
大多数测试将保持不变并使用默认值。
it_behaves like 'it accepts uploads'
您的例外可以指定它们的格式。
it_behaves like 'it accepts uploads', formats: [:yaml, :json]
如果比这更复杂,您可能希望将共享测试分解为针对每种格式的单独测试。原始共享测试运行所有单独的共享测试。离群值可以随意挑选。
shared_examples 'it accepts uploads in all formats' do
it_behaves_like 'it accepts yaml uploads'
it_behaves_like 'it accepts json uploads'
it_behaves_like 'it accepts csv uploads'
end
同样,大多数测试保持不变。
it_behaves_like 'it accepts uploads in all formats'
并且异常值可以单独运行测试。
it_behaves_like 'it accepts yaml uploads'
it_behaves_like 'it accepts json uploads'
这具有分解可能是大型共享示例的额外优势,并允许进一步自定义单个共享示例。
为了方便,您可以将两者结合起来。
shared_examples 'it accepts uploads' do |formats: [:yaml, :json, :csv]|
it_behaves_like 'it accepts yaml uploads' if formats.include?(:yaml)
it_behaves_like 'it accepts json uploads' if formats.include?(:json)
it_behaves_like 'it accepts csv uploads' if formats.include?(:csv)
end