Reputation: 5220
I know that starting with Rails 5.0 I can add as: :json
attribute to send the test HTTP request with application/json
content type like this:
post :create, params: { account_id: 123, user: { ... } }, as: :json
Is there a way to configure this behavior globally, so that I don't need to specify the content type on each test?
I'm upgrading from Rails 4.2 and realised that without this attribute all my requests are treated as URL encoded forms, including my payload being URL encoded. This is causing many failures when I run my test suite and for some reason was working just fine in Rails 4.2.
Upvotes: 0
Views: 495
Reputation: 102036
You could always just override ActionDispatch::Integration::RequestHelpers#process
.
module JSONRequestHelper
alias_method :original_process, :process
def process(method, path, **args)
original_process(method, path, args.merge(as: :json))
end
end
require 'test_helper'
class ApiTest < ActionDispatch::IntegrationTest
include JSONRequestHelper
end
Upvotes: 1
Reputation: 778
You can specify in your routes the default format for them, like so:
defaults format: :json do
resources :photos
end
as can be seen here: https://guides.rubyonrails.org/routing.html#defining-defaults
You can always use a before_action as well:
before_action :set_format
def set_format
request.format = 'json'
end
Upvotes: 1