I\'m using the rails-api gem to build a web service and want to test my API with RSpec. Every request I make, regardless of the HTTP method has the CONTENT_TYPE
hea
Using the new Rails v5.0.x API only settings I found that this problem with rails defaulting everything to "application/x-www-form-urlencoded"
is still in issue for testing with RSpec-Rails Requests
Here is what I did to fix the problem:
Create support file at ./spec/support/json_requests.rb
Edit it to be something like this to override the behavior for all of your API only JSON requests:
module JsonRequests
def get(*args)
super(*json_args(*args))
end
def post(*args)
super(*json_args(*args))
end
def update(*args)
super(*json_args(*args))
end
def patch(*args)
super(*json_args(*args))
end
def put(*args)
super(*json_args(*args))
end
def delete(*args)
super(*json_args(*args))
end
def json_args(path, params = {}, headers = {})
[path, params.to_json, headers.merge('CONTENT_TYPE' => 'application/json')]
end
end
RSpec.configure do |config|
config.include JsonRequests, type: :request
end
Keep in mind that this will override all Specs within ./spec/requests
so if you need to use "application/x-www-form-urlencoded"
you could also include
this module manually as needed in your Describe 'something' do
block.