Schasus
Schasus

Reputation: 11

Why can't I create user in spec?

I have a problem with RSpec, my request_spec /post keep giving me output:

1) Users POST /users valid user  creates user properly
     Failure/Error: expect(json['title']).to eq("[email protected]")

       expected: "[email protected]"
            got: nil

       (compared using ==)
     # ./spec/requests/users_request_spec.rb:54:in `block (4 levels) in <main>'

  2) Users POST /users valid user  have http status 201
     Failure/Error: expect(response).to have_http_status(201)
       expected the response to have status code 201 but it was 422
     # ./spec/requests/users_request_spec.rb:59:in `block (4 levels) in <main>'

  3) Users POST /users invalid user  return failure message
     Failure/Error: @user = User.create!(user_params)

     ActiveRecord::RecordInvalid:
       Validation failed: Password can't be blank, Password is too short (minimum is 5 characters), Email can't be blank, Email is invalid, Email has already been taken, Password confirmation can't be blank

My spec is:

describe 'POST /users' do
        let(:valid_params) { { email: '[email protected]', password: '12345678', password_confirmation: '12345678', name: 'Derek' } }


        context 'valid user ' do
            before { post "/users", params: valid_params }

            it 'creates user properly' do
                puts user.errors.size
                expect(json['title']).to eq("[email protected]")
                expect(json).not_to be_empty
            end

            it 'have http status 201' do
                expect(response).to have_http_status(201)
            end
        end

        context 'invalid user ' do
            before { post "/users", params: { } }

            it 'return failure message' do
                expect(response.body).to match(/Email can't be blanc/)
            end

        end
    end

And controller:

def create
        # @user.id = current_user.id
        @user = User.create!(user_params)

        respond_to do |format|
            if @user.save
                format.json { render json: @user, status: :created }
            else
                format.json { render json: @user.errors, status: :unprocessable_entity }
            end
        end
    end

I thought it was problem with user params:

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

and i added require(:user) to it, but then i got error 'param is missing or value is empty user'. I can't handle it, please help me.

Upvotes: 1

Views: 332

Answers (1)

Greg
Greg

Reputation: 6628

Keep require(:user) and change the valid_params in spec like this:

let(:valid_params) { {user: { email: '[email protected]', password: '12345678', password_confirmation: '12345678', name: 'Derek'}} } 

Upvotes: 1

Related Questions