---
title: "Specific mime types in controller tests in Rails 5"
description:
  "We can provide a specific mime type to a request using `as` option in Rails 5"
canonical_url: "https://www.bigbinary.com/blog/use-as-option-to-encode-request-with-specific-mime-type-in-rails-5"
markdown_url: "https://www.bigbinary.com/blog/use-as-option-to-encode-request-with-specific-mime-type-in-rails-5.md"
---

# Specific mime types in controller tests in Rails 5

We can provide a specific mime type to a request using `as` option in Rails 5

- Author: Abhishek Jain
- Published: July 5, 2016
- Categories: Rails 5, Rails

Before Rails 5, while sending requests with integration test setup, we needed to
add `format` option to send request with different `Mime type`.

```ruby

class ProductsControllerTest < ActionController::TestCase
  def test_create

    post :create, { product: { name: 'Rails 5 book' } }.to_json,
        format: :json,
        headers: { 'Content-Type' => 'application/json' }

    assert_equal 'application/json', request.content_type
    assert_equal({ id: 1, name: 'Rails 5 book' }, JSON.parse(response.body))
  end
end

```

This format for writing tests with `JSON` type is lengthy and needs too much
information to be passed to request as well.

## Improvement with Rails 5

In Rails 5, we can provide `Mime type` while sending request by
[passing it with as option](https://github.com/rails/rails/pull/21671) and all
the other information like `headers` and format will be passed automatically.

```ruby

class ProductsControllerTest < ActionDispatch::IntegrationTest
  def test_create
    post products_url, params: { product: { name: 'Rails 5 book' } }, as: :json

    assert_equal 'application/json', request.content_type
    assert_equal({ 'id' => 1, 'name' => 'Rails 5 book' }, response.parsed_body)
  end
end

```

As we can notice, we don't need to parse JSON anymore.

With changes in this [PR](https://github.com/rails/rails/pull/23597), we can
fetch parsed response without needing to call `JSON.parse` at all.

## Custom Mime Type

We can also register our own encoders for any registered `Mime Type`.

```ruby

class ProductsControllerTest < ActionDispatch::IntegrationTest

  def setup
    Mime::Type.register 'text/custom', :custom

    ActionDispatch::IntegrationTest.register_encoder :custom,
      param_encoder: -> params { params.to_custom },
      response_parser: -> body { body }

  end

  def test_index
    get products_url, params: { name: 'Rails 5 book' }, as: :custom

    assert_response :success
    assert_equal 'text/custom', request.content_type
  end
end

```

## Links

- [Human page](https://www.bigbinary.com/blog/use-as-option-to-encode-request-with-specific-mime-type-in-rails-5)
