Reputation: 3527
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.
Upvotes: 1
Views: 94
Reputation: 44370
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")
Upvotes: 1