10
8

More than 5 years have passed since last update.

Rails5でJSON APIのテストする際、POSTのパラメーターとして渡した2次元配列が展開されてしまう問題の対処法

Last updated at Posted at 2017-09-11

ActionController::TestCaseの仕様なのでRspecに限らないが、例えばRspecを使用した場合。

it 'POSTでリソースが作成できる' do
  params = { paris: [[1, 2], [3, 4]] }
  post '/resources', params
  expect(response).to have_http_status :created
end

ブラウザからは問題なくリソースの作成が行えるがテストはコケる。

原因を調べるためにコントローラー側でbinding.pryすると
以下のようにparamsが展開されてしまっていることが分かった。

params[:paris] # => ["1", "2", "3", "4"]

解決するにはpostas: :jsonオプションを渡してあげればいい。

it 'POSTでリソースが作成できる' do
  params = { paris: [[1, 2], [3, 4]] }
  post '/resources', params, as: :json
  expect(response).to have_http_status :created
end

参考:
Allow setting of request CONTENT-TYPE with as: in controller tests

問題が起きた原因はテスト時のデフォルトのContent-Typeがapplication/x-www-form-urlencodedであること。
ネストされていない配列だったら問題ないがネストされた配列だと、パラメーターのparse時に構造が失われてしまう。

JSON形式で送ればパラメータの構造は維持されるので問題は起きない。

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8