Render the full Json array in response.body - ruby-on-rails

This test keeps failing Im not sure what to do. I am guessing a fix would be to render the raw Json array but I am utterly lost.
error
NoMethodError: undefined method []' for nil:NilClass
/Users/newuser/railschallenge-city-watch/test/api/emergencies_create_test.rb:10:inblock in '
emergencies controller
def create
#emergency = Emergency.new(emergency_params)
if #emergency.save
render json: #emergency.to_json , :status => 201
end
end
test 'POST /emergencies/ simple creation' do
post '/emergencies/', emergency: { code: 'E-99999999', fire_severity: 1, police_severity: 2, medical_severity: 3 }
json_response = JSON.parse(response.body)
assert_equal 201, response.status
assert_equal nil, body['message']
assert_equal 'E-99999999', json_response['emergency']['code']
assert_equal 1, json_response['emergency']['fire_severity']
assert_equal 2, json_response['emergency']['police_severity']
assert_equal 3, json_response['emergency']['medical_severity']
end

Try this:
render json: #emergency.to_json(:root => "emergency"), :status => 201

render json: {"emergency" => #emergency}.to_json , :status => 201

Related

Render is not giving the response in rails

In my application the render is not showing the response on browsers console.
my controller class is-
def create
ActionItem.transaction do
#action = #doc.action_items.new(action_item_params)
#action.minutes_section = #section if #section
# Were we passed a sort_order? If not, default to the highest sort
# order number for this action item's section. minutes-app may
# also pass us -1 to indicate we should compute the next value.
if !action_item_params.key?(:sort_order) or [-1, nil, ""].include?(action_item_params[:sort_order])
result = ActionItem.where(minutes_document_id: #doc.id, minutes_section_id: #section.id).maximum('sort_order')
if result.nil?
#action.sort_order = 0
else
#action.sort_order = result + 1
end
end
if #action.save!
#action.action_items_statuses.create!(status: 'incomplete', status_type: 'completion', contact_id: current_user.id)
#action.action_items_statuses.create!(status: 'unsent', status_type: 'notification', contact_id: current_user.id)
#action.action_items_statuses.reload
handle_assignees(#action, params[:data][:attributes][:assignees]) if !params[:data][:attributes][:assignees].blank?
handle_note(#action, params[:data][:attributes][:note])
render(json: #action, status: 201)
else
render(json: { error: #action.errors }, status: 500)
end
end
rescue ActiveRecord::ActiveRecordError => e
Rails.logger.error e.message
render(json: { error: e.message }, status: 500)
end
I am not getting the response on console-
Error

How to send location after `create` action

I have the following create action:
def create
episode = Episode.new(episode_params)
if episode.save
render json: episode, status: :created, location: episode
end
end
but when I test the following:
require 'test_helper'
class CreatingEpisodesTest < ActionDispatch::IntegrationTest
setup { host! 'api.example.com'}
test 'create episodes' do
post '/episodes',
{ episode:
{ title: 'Bananas', description: 'Learn about bananas.' }
}.to_json,
{ 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s }
assert_equal 200, response.status
assert_equal Mime::JSON, response.content_type
episode = json(response.body)
assert_equal "/episodes/#{episode[:id]}", response.location
end
end
I get the following error:
1) Error: CreatingEpisodesTest#test_create_episodes: NoMethodError: undefined method `episode_url' for #<API::EpisodesController:0x007f8e34519450> Did you mean? episode_params
app/controllers/api/episodes_controller.rb:11:in `create'
test/integration/creating_episodes_test.rb:7:in `block in #<class:CreatingEpisodesTest>'
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
I guest I miss something to send the location after I create the episode.
UPDATE: Route
Rails.application.routes.draw do
namespace :api, path: '/', constraints: { subdomain: 'api' } do
resources :zombies
resources :episodes
end
end
This is because of namespace, use [:api, episode] for location

Params for json array in Rails

I'm new to rails,
Please check my code and tell me whats wrong with my use params, because this is how it made sense to me.
Controller:
def create
user = User.find(user_params)
order = user.purchases.new
render json: order.errors if !order.save
basket = params.require(:basket)
basket.each do |b|
i = Item.find(b[:item_id])
render json: i.errors, status: 422 if !i
order.purchases_items.create(item_id: i, quantity: b[:quantity])
end
render nothing: true, status: 201 # location: show action
end
and my test file is sending
test "making order" do
post "/api/users/#{#tuser.id}/orders",
{ basket: [ { item_id: '2', quantity: '5' },
{ item_id: '1', quantity: '4'} ] }.to_json,
{ 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s }
assert_response 201
assert_equal Mime::JSON, response.content_type
end
Thanks,
What I basically want to do is store each array element in the array basket from params[:basket], and iterate over it.
Sometime params keys are not get converted into symbols automatically. Can u try passing string "basket" instead of symbol :basket?

Issue with apipie gem and rspec in rails 4

i'm writing the code to get my Rspec tests to pass on my api. I'm using the apipie gem to generate documentation and it seems that my tests are failing because thy are expecting a number and it's funny because this is exactly what I want to test.
The page fails when the :bpm parameter is not a number. is there any way of going around this ?
context "when is not created" do
before(:each) do
user = FactoryGirl.create :user
#invalid_lesson_attributes = { title: "California Dreamin",
bpm: "Hello"
}
request.headers['Authorization'] = user.auth_token
post :create, { user_id: user.id, lesson: #invalid_lesson_attributes }
end
it "renders an errors json" do
lesson_response = json_response
expect(lesson_response).to have_key(:errors)
end
it "renders the json errors on why the user could not be created" do
lesson_response = json_response
expect(lesson_response[:errors][:bpm]).to include "is not a number"
end
it { should respond_with 422 }
end
end
Update spec:
context "when is not updated" do
before(:each) do
patch :update, { user_id: #user.id, id: #lesson.id,
lesson: { bpm: "ten" }, format: :json }
end
it "renders an errors json" do
lesson_response = json_response
expect(lesson_response).to have_key(:errors)
end
it "renders the json errors on why the user could not be updated" do
lesson_response = json_response
expect(lesson_response[:errors][:bpm]).to include "is not a number"
end
it { should respond_with 422 }
end
in my users_controller:
api :POST, '/teachers/:user_id/lessons/', "Create lesson"
param :lesson, Hash, desc: 'Lesson information', :required => true do
param :title, String, desc: 'Title of the lesson', :required => true
param :bpm, :number, desc: 'tempo of the lesson (beats per second)', :required => true
end
error :code => 422, :desc => "Unprocessable Entity"
my error when I run my rspec tests :
Apipie::ParamInvalid: Invalid parameter 'bpm' value "Hello": Must be a number.
Adds format json to post request
post :create, { user_id: user.id, lesson: #invalid_lesson_attributes, format: :json }
That worked for me.

Spec - simple json api call

I just want to test that a controller method is passing an int.
Test:
it 'responds successfully with mocked fto hours remaining' do
get :fto_hours_remaining, {}, { "Accept" => "application/json" }
json = JSON.parse(response.body)
expect(json['hours_remaining']).to be_100
end
Controller method (I tried the commented out block too):
def fto_hours_remaining
#fto_hours_remaining = 100
render json: #fto_hours_remaining
# respond_to do |format|
# format.json { render :json => {:hours_remaining => #fto_hours_remaining} }
# end
end
I get the error: JSON::ParserError: 757: unexpected token at '100' with the error pointing to json = JSON.parse(response.body)
Anybody see a mistake? Thanks.
So you have right version in your controller:
def fto_hours_remaining
#fto_hours_remaining = 100
render :json => { :hours_remaining => #fto_hours_remaining }
end
Your action now render just string 100 this is invalid json.
Try in irb:
=> require 'json'
=> true
=> JSON.parse "100"
=> JSON::ParserError: 757: unexpected token at '100'
render( json: { hours_remaining: #fto_hours_remaining } ) means render me in json format this hash { hours_remaining: #fto_hours_remaining } that should be valid json:
{
"hours_remaining": 100
}
And your test:
# return string "100"
number = json['hours_remaining']
# fails beacause "100" != 100
expect(json['hours_remaining']).to be_100
# try this
expect(json['hours_remaining']).to eq("100")

Resources