This is adapted from https://stackoverflow.com/a/39399215/544825 but for controller specs.
Tested on: RSpec 3.8, Rails 5.2.1
This module uses metaprogramming to redefine the get
, post
etc methods and a memoized let
helper (default_format
) instead of metadata.
It basically just merges format: default_format
into the arguments and calls the original implementation.
# spec/support/default_format.rb
module DefaultFormat
extend ActiveSupport::Concern
included do
let(:default_format) {}
prepend RequestHelpersCustomized
end
module RequestHelpersCustomized
l = lambda do |path, **kwargs|
kwargs[:format] ||= default_format if default_format
super(path, kwargs)
end
%w(get post patch put delete).each do |method|
define_method(method, l)
end
end
end
And then include this module in your rails_helper.rb
or spec_helper.rb
(if you only have one test setup file):
require 'support/default_format'
RSpec.configure do |config|
# ...
config.include DefaultFormat, type: :controller
# ...
end
Usage:
context 'json' do
let(:default_format) { :json }
end
I don't think this can be done with example metadata as its not available from within an example (which is where the get
method is called).