I'm using shared_examples
in RSpec to run a group of tests for multiple upload formats such as yml, csv, etc. for many different rspec files. However, one of my rspec tests that are running these shared examples, does not support csv upload formats. Is it possible to disable/skip certain csv tests in the shared examples for this one rspec file?
One option is to add the allowed upload formats to your controller and have the tests introspect your controllers. This will likely DRY up both the production and test code.
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
This might be too DRY; if self.upload_formats
is missing a format the tests will not catch it.
You could add a flag to the shared examples and pass in which formats it should check. If the test for each format is similar, this becomes a simple loop.
shared_examples 'it accepts uploads' do |formats: [:yaml, :json, :csv]|
formats.each do |format|
let(:format) { format }
context "in #{format}" do
...
end
end
end
Most tests will remain unmodified and use the defaults.
it_behaves like 'it accepts uploads'
Your exceptions can specify their formats.
it_behaves like 'it accepts uploads', formats: [:yaml, :json]
If it's more complicated than that, you may wish to break the shared test down into a separate test for each format. The original shared test runs all the individual shared tests. The outliers can pick and choose.
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
Again, most tests remain the same.
it_behaves_like 'it accepts uploads in all formats'
And the outliers can run tests individually.
it_behaves_like 'it accepts yaml uploads'
it_behaves_like 'it accepts json uploads'
This has the additional advantages of breaking up what might be a large shared example, and allowing individual shared examples to be further customized.
And you can combine the two for convenience.
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