The get_children method of my Playgrounds controller renders a specific javascript template, or json formated data:
# GET children from playground
def get_children
@business_areas = @playground.business_areas.visible.order(:sort_code)
respond_to do |format|
format.json { render json: @business_areas }
format.js # uses specific template to handle js
end
end
When requesting this method with Rspec tests, I get the following error message: ActionController::UnknownFormat
. For the test, the playground and one child business area have been created in advance:
describe "get_children - GET /playgrounds/:id/get_children" do
it "renders a successful response" do
get get_children_playground_url(playground)
expect(response).to be_successful
end
it "renders the expected object" do
get get_children_playground_url(playground)
parsed_body = JSON.parse(response.body)
expect(parsed_body[:name][:en]).to eq('Test Business Area')
end
end
Reading around, I found some references about request.accept = "application/json"
but I didn't manage to have it working.
How and where shall I set the expected output format for the method call?
Thanks for yout help!
PS: RSpec version is 3.12
describe "GET /playgrounds/:id/get_children" do
it "renders an html response" do
get get_children_playground_url(playground)
expect(response.content_type).to eq "text/html; charset=utf-8"
end
it "renders a json response" do
# NOTE: using Accept header
# get get_children_playground_url(playground), headers: {Accept: "application/json"}
# NOTE: using .json url extension
get get_children_playground_url(playground, format: :json)
expect(response.content_type).to eq "application/json; charset=utf-8"
end
it "renders a js response" do
# get get_children_playground_url(playground), headers: {Accept: "text/javascript", HTTP_X_REQUESTED_WITH: "XMLHttpRequest"}
# NOTE: there is an option for all that ^ ^ this one is to avoid cross origin error
get get_children_playground_url(playground), xhr: true
expect(response.content_type).to eq "text/javascript; charset=utf-8"
end
end
...
renders an html response
renders a json response
renders a js response
Finished in 0.32929 seconds (files took 1.48 seconds to load)
3 examples, 0 failures
https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html#method-i-process