DEV Community

loading...

Test Rails API with json type

Dmitry Daw
・1 min read

By default Rails converts all params that come from Rspec to strings(related issue https://github.com/rails/rails/issues/26075)

For example, { my_type: 1 } will become { "my_type": "1" }

So to keep our types as they should be we can write our requests from test as so:

  get :create, params: params, as: :json
Enter fullscreen mode Exit fullscreen mode

But it also possible to define json type for all requests in test file:

  before do
    request.accept = 'application/json'
    request.content_type = 'application/json' 
  end
Enter fullscreen mode Exit fullscreen mode

And now we can skip that as: :json part.

And with Rspec shared_examples we can easily reuse that:

# rails_spec.rb
RSpec.shared_context 'json_api' do
  before do
    request.accept = 'application/json'
    request.content_type = 'application/json'
  end
end

# our_controller_spec.rb
RSpec.describe OurController, type: :controller do
  include_context 'json_api'

  # ... tests
Enter fullscreen mode Exit fullscreen mode

Discussion (0)