Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Rspec default GET request format to JSON

I am doing functional tests for my controllers with Rspec. I have set my default response format in my router to JSON, so every request without a suffix will return JSON.

Now in rspec, i get an error (406) when i try

get :index

I need to do

get :index, :format => :json

Now because i am primarily supporting JSON with my API, it is very redundant having to specify the JSON format for every request.

Can i somehow set it to default for all my GET requests? (or all requests)

like image 736
Drazen Avatar asked Jun 13 '12 20:06

Drazen


2 Answers

before :each do
  request.env["HTTP_ACCEPT"] = 'application/json'
end
like image 87
Pratik Khadloya Avatar answered Oct 23 '22 16:10

Pratik Khadloya


Put this in spec/support:

require 'active_support/concern'

module DefaultParams
  extend ActiveSupport::Concern

  def process_with_default_params(action, parameters, session, flash, method)
    process_without_default_params(action, default_params.merge(parameters || {}), session, flash, method)
  end

  included do
    let(:default_params) { {} }
    alias_method_chain :process, :default_params
  end
end

RSpec.configure do |config|
  config.include(DefaultParams, :type => :controller)
end

And then simply override default_params:

describe FooController do
    let(:default_params) { {format: :json} }
    ...
end
like image 25
knoopx Avatar answered Oct 23 '22 14:10

knoopx