4

Rails4(4.2.0.rc1)でコントローラーのPOSTアクションのテストを書こうとしたのですが、ActionController::ParameterMissing のエラーでテストできません。

コントローラー

class UsersController < ApplicationController

  # ... 省略 ...

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to Sample App!"
      log_in @user
      redirect_to @user
    else
      render 'new'
    end
  end

  # ... 省略 ...

テスト

require 'test_helper'

class UsersControllerTest < ActionController::TestCase

  test "should post create" do
    post :create,
         name: "abc",
         email: "[email protected]",
         password: "passwd",
         password_confirmation: 'passwd'
    assert_response :success
  end
end

エラー

 test_should_post_create#UsersControllerTest (0.64s)
ActionController::ParameterMissing:         ActionController::ParameterMissing: param is missing or the value is empty: user
            app/controllers/users_controller.rb:37:in `user_params'
            app/controllers/users_controller.rb:11:in `create'
            test/controllers/users_controller_test.rb:10:in `block in <class:UsersControllerTest>'
        app/controllers/users_controller.rb:37:in `user_params'
        app/controllers/users_controller.rb:11:in `create'
        test/controllers/users_controller_test.rb:10:in `block in <class:UsersControllerTest>'

Webブラウザ上のフォームでは実行できていて、POSTパラメータをのぞくと、テストで指定しているのと同じname, email, password, password_confirmation が入っていました。
どうすればエラーなく実行できますか?

1
  • testingのタグを追加しました。
    – tomute
    2014年12月20日 11:55

1 件の回答 1

3

自己解決してしまいました。

post :create,
     user: {
       name: "abc",
       email: "[email protected]",
       password: "passwd",
       password_confirmation: 'passwd'
     }

の形のハッシュをパラメータにしないといけませんでした。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。