LoginSignup
35
23

More than 5 years have passed since last update.

RSpecのrequest specでパラメータが正しく認識されない問題の対処法

Posted at

RSpec 3.8 のRequest Specを使っていると、時おりリクエストパラメータが正しくRailsに届いてくれない問題に遭遇することがあったので、対策を書き残しておきます。

環境

  • Rails 5.2.2.1
  • RSpec 3.8
    • rspec-core 3.8.0
    • rspec-expectations 3.8.2
    • rspec-mocks 3.8.0
    • rspec-rails 3.8.2
    • rspec-support 3.8.0

問題

booleanや数値が文字列に変換されてしまう

# RSpec側
post xxxx_path, params: { foo: 1, bar: true }

# Rails側
# => <ActionController::Parameters {"foo"=>"1", "bar"=>"true", "controller"=>"xxx", "action"=>"xxx"} permitted: false>

空の配列になぜか空の文字列が含まれてしまう

# RSpec側
post xxxx_path, params: { foo: [] }

# Rails側
# => <ActionController::Parameters {"foo"=>[""], "controller"=>"xxx", "action"=>"xxx"} permitted: false>

対処法

  • headers に { "Content-Type" => "application/json" } を追加した上で、パラメータのハッシュを to_json で文字列に変換してから送信する。
# RSpec側
post xxxx_path, params: { foo: 1, bar: true, hoge: [] }.to_json, headers: { "Content-Type" => "application/json" }

# Rails側
# => <ActionController::Parameters {"foo"=>1, "bar"=>true, "hoge"=>[], "controller"=>"xxx", "action"=>"xxx"} permitted: false>

ちなみに

  • 空の配列に空文字が含まれてしまう問題だけについて言えば、Gemfileで rack-test のバージョンを < 0.7.0 に指定すれば解消できる。
  • 参考: stackoverflow
35
23
1

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
35
23