7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【RSpec】POSTリクエストパラメータの数値が文字列になってしまう

Last updated at Posted at 2020-07-18

解決策

as: :json オプションをつける。

post '/posts', params: post_params, as: :json

解説

rspecのデフォルトのCONTENT_TYPEはapplication/x-www-form-urlencoded なので、適切に文字列に変換してくれてます、jsonを送信する場合はapplication/jsonに書き換えるのが最良だと思います
https://sinshutu-kibotu.hatenablog.jp/entry/2018/07/06/202132

なるほど。

サンプルコード

RSpec.describe 'post add', type: :request do
  describe 'POST /posts' do
    context '投稿記事作成' do
      let(:post_params) do
        {
          age: 2,
          sex: 'female',
          status: 0,
          answer: {
            text: '初の投稿です。',
            score: 1
          }
        }
      end

      it 'create posts' do
        expect do
          post '/posts', params: post_params, as: :json
        end.to change { Post.count }.by(1)
      end
    end

所感

ActiveModel::Attributesで型をcastする、というアプリケーション側での解決策も不可能ではない気がした(が、サンプルコードのようにパラメータがネストしていると大変だったため断念)。

参考リンク

7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?