fernal9301 fernal9301 - 1 year ago 137
JSON Question

howto properly rails api rspec json test

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)>'

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download