11
9

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 5 years have passed since last update.

rails4系で request spec で post すると、数値が文字列として解釈される問題

Posted at

こんなmodel

$ rails g scaffold user name:string, role:integer
app/models/user.rb
class User < ActiveRecord::Base
  enum role: { worker: 1, manager: 0 }

  validates :role,
    inclusion: {in: User.roles.keys}
end

こんなテスト

spec/requests/users_spec.rb
require 'rails_helper'

RSpec.describe "Users", type: :request do
  describe "POST /user" do
    subject do
      post users_path, user: { name:'name', role:1 }
    end
    it { expect{subject}.to change{User.all.size}.from(0).to(1) }
  end
end

結果

  1) Users POST /user
     Failure/Error: @user = User.new(user_params)

     ArgumentError:
       '1' is not a valid role

ナンデ? きちんと intger の 1 渡したよ!?

  • paramの扱いが、controllerでテストするときと異なるらしい

どうしたら良いの?

応急処置的には、JSONフォーマットで渡せば良い

.rb
      #post users_path, user: { name:'name', role:1 }
      post users_path, { name:'name', role:1 }.to_json, CONTENT_TYPE: 'application/json'

応急処置以外だと?

そもそも request でテストしないということを推奨している人もいる

上の人はRails4だとうまくいかないと言っていたけど、Rails5ならどう?

Rails5.0.0.1で試してみたけど再現した

参考

11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?