DEV Community

zato
zato

Posted on

2

Don't forget `as: :json` when testing JSON API

When you write tests for your JSON API with request spec, typical code is like:

describe 'POST /restaurants' do
  let(:params) { { name: 'pizza foobar' } }

  it 'creates a restaurant' do
    post '/restaurants', headers: headers, params: params
    expect(response).to have_http_status(:created)
    expect(response.parsed_body).to match(
      'id' => String,
      'name' => 'pizza foobar'
    )
  end
end
Enter fullscreen mode Exit fullscreen mode

But this doesn't test the API right, technically.

Because this test sends a POST request with application/x-www-form-urlencoded, not application/json.

Mostly, you expect request body with application/json for JSON API. This code does not simulate requests properly.

So, use as: :json option:

post '/restaurants', headers: headers, params: params, as: :json
Enter fullscreen mode Exit fullscreen mode

I'm lazy enough to avoid passing as: :json every time.

Usually I override those helpers to pass as: :json option by default:

module RequestHelper
  %i[get post patch put delete].each do |method_name|
    define_method(method_name) do |path, args = {}|
      default_options = { as: :json }
      process method_name, path, default_options.merge(args)
    end
  end
end

RSpec.configure do |config|
  config.include RequestHelper, type: :request
  # ...
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
haukot profile image
Dmitry Daw

Interesting solution! I can also propose to do it in that way dev.to/haukot/test-rails-api-with-... - we don't need to redefine our methods in it.

Collapse
 
schmijos profile image
Josua Schmid

This post is about request specs.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →