Test Rails API with json type
Dmitry Daw

Dmitry Daw @haukot

Joined:
Jul 3, 2019

Test Rails API with json type

Publish Date: Apr 5 '21
7 1

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

Comments 1 total

  • Josua Schmid
    Josua SchmidMar 6, 2024

    Important note: this is about controller specs.

Add comment