Last active
February 28, 2018 21:48
-
-
Save adavia/c0ca1ea77e6e66e12e21e2482f4dbf65 to your computer and use it in GitHub Desktop.
RSpec sending raw JSON parameters post request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| describe 'POST /books' do | |
| # valid payload | |
| let(:valid_attributes) do | |
| # send stringify json payload | |
| { | |
| "title": "Learn Elm", | |
| "user_id": user.id, | |
| "image": "example.jpg" | |
| }.to_json | |
| end | |
| # Controller error: no implicit conversion of ActiveSupport::HashWithIndifferentAccess into String | |
| context 'when the request is valid' do | |
| before { post '/books', params: valid_attributes, headers: headers } | |
| it 'creates a books' do | |
| expect(json['book']['title']).to eq('Learn Elm') | |
| end | |
| it 'returns status code 201' do | |
| expect(response).to have_http_status(201) | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def create | |
| @book = current_user.books.create!(book_params) | |
| render json: @book, status: :created | |
| end | |
| def book_params | |
| parsed = JSON.parse(request.params[:book]) # request.params[:book] => HASH | |
| params = ActionController::Parameters.new(parsed) | |
| params['image'] = request.params[:image] | |
| params.permit(:title, :image, :user) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment