1

I've got UsersController

def create
  @user = User.create(user_params)
  if @user.save
    render json: @user, status: :created
  else
    render json: @user, status: :unprocessable_entity
  end
end

I need to test this create action with RSPec. Can you please help, how to do it properly

I'm stuck with this code

RSpec.describe UsersController, type: :controller do
  # Test for POST /users
  describe 'POST /users' do
    let(:user) { User.create(email: '[email protected]', password: 'abc123', token: 'anytokenhere') }
    context '#check valid request' do

      before { post 'create', params: user }

      it 'creates a user' do
        json = JSON.parse(response.body)
        expect(json['email']).to eq('[email protected]')
        expect(json['password']).to eq('abc123')
      end

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end

  end
end

got the following error:

Failures:

  1) UsersController POST /users #check valid request creates a user
     Failure/Error: before { post 'create', params: user }

     NoMethodError:
       undefined method `symbolize_keys' for #<User:0x0055f95cee9a48>
     # ./spec/controllers/users_controller_spec.rb:9:in `block (4 levels) in <top (required)>'

  2) UsersController POST /users #check valid request returns status code 201
     Failure/Error: before { post 'create', params: user }

     NoMethodError:
       undefined method `symbolize_keys' for #<User:0x0055f95cbebbc0>
     # ./spec/controllers/users_controller_spec.rb:9:in `block (4 levels) in <top (required)>'
1

1 Answer 1

1

The problem is that you provide User model as a params when Hash is expected.

This is an example of a post request to /users that works:

RSpec.describe UsersController, type: :controller do
  # Test for POST /users
  describe 'POST /users' do
    let(:user) { User.last }

    context '#check valid request' do
      before { post 'create', params: { user: { email: '[email protected]', password: 'abc123', token: 'anytokenhere' } } }

      it 'creates a user' do
        json = JSON.parse(response.body)
        expect(user.email).to eq('[email protected]')
      end

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end

  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! You're so fast. It works. As I understand line ``` let(:user) { User.last } ``` is optional, everything works just fine without it.
let(:user) { User.last } is to get the last user (just created) and verify its email. But, certainly it's up to you how to design your code :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.