DEV Community

Dmitry Daw
Dmitry Daw

Posted on

3 2

Test Rails API with json type

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (1)

Collapse
 
schmijos profile image
Josua Schmid

Important note: this is about controller 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 →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay