CamelWriter
CamelWriter

Reputation: 137

Param is missing in rspec test

I have the following RSpec test defined:

test 'invalid signup information' do
    get signup_path
    assert_no_difference 'User.count' do
        post users_path, params: { user: { name:  '',
                                           email: 'user@invalid',
                                           password:              'foo',
                                           password_confirmation: 'bar' } }
    end
    assert_template 'users/new'
end

And the following Controller:

class UsersController < ApplicationController

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to new_user_path
    else
      render :new
    end
  end

  def show
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end

If I execute rake test I get the following error:

ERROR["test_invalid_signup_information", UserSignupTest, 0.35556070700022246]
 test_invalid_signup_information#UserSignupTest (0.36s)
ActionController::ParameterMissing:         ActionController::ParameterMissing: param is missing or the value is empty: user
            app/controllers/users_controller.rb:23:in `user_params'
            app/controllers/users_controller.rb:8:in `create'
            test/integration/user_signup_test.rb:7:in `block (2 levels) in <class:UserSignupTest>'
            test/integration/user_signup_test.rb:6:in `block in <class:UserSignupTest>'

The test runs without problems if i delete the require statement in user_params. But I do send a user - So why does it fail?

Upvotes: 0

Views: 1483

Answers (1)

Breno Perucchi
Breno Perucchi

Reputation: 893

I do not if this is right but in my opinion, you created an integration test but should be a test controller.

See this example

# spec/controllers/contacts_controller_spec.rb

# rest of spec omitted ...

describe "POST create" do
  context "with valid attributes" do
    it "creates a new contact" do
      expect{
        post :create, contact: {name: 'test'}
      }.to change(Contact,:count).by(1)
    end

more info for integration test

Upvotes: 1

Related Questions