我正在RSpec中使用shared_examples
对多种不同的rspec文件的yml,csv等多种上传格式运行一组测试。但是,我的运行这些共享示例的rspec测试之一不支持csv上传格式。是否可以在此rspec文件的共享示例中禁用/跳过某些csv测试?
一种选择是将允许的上传格式添加到您的控制器,并使测试自检您的控制器。这可能会使生产代码和测试代码都变干。
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