如何在RSpec请求测试中指定特定响应格式?
解决RSpec测试中ActionController::UnknownFormat错误
你的get_children控制器方法仅支持json和js两种响应格式,但测试发起的GET请求未指定格式,导致控制器无法匹配响应规则,抛出ActionController::UnknownFormat错误。以下是几种有效的解决方式:
方式一:在GET请求中直接指定format参数
这是最直观的做法,在get方法调用时通过format: :json明确指定响应格式:
describe "get_children - GET /playgrounds/:id/get_children" do it "renders a successful response" do get get_children_playground_url(playground), format: :json expect(response).to be_successful end it "renders the expected object" do get get_children_playground_url(playground), format: :json parsed_body = JSON.parse(response.body) # 注意:JSON.parse返回的哈希使用字符串键,而非符号键 expect(parsed_body.first["name"]["en"]).to eq('Test Business Area') end end
方式二:设置请求的Accept请求头
若要通过设置请求头指定格式,需确保在发起get请求之前设置request.accept:
describe "get_children - GET /playgrounds/:id/get_children" do it "renders a successful response" do request.accept = "application/json" get get_children_playground_url(playground) expect(response).to be_successful end it "renders the expected object" do request.accept = "application/json" get get_children_playground_url(playground) parsed_body = JSON.parse(response.body) expect(parsed_body.first["name"]["en"]).to eq('Test Business Area') end end
之前设置未生效大概率是因为顺序错误,必须先设置请求头再发起请求。
方式三:在路由辅助方法中指定格式
也可以直接在路由辅助方法的参数里添加格式指定:
get get_children_playground_url(playground, format: :json)
效果与方式一完全一致。
扩展:测试JS格式响应
如果需要测试js格式的响应,只需将对应格式参数或请求头替换为js格式即可:
- 使用参数:
format: :js - 使用请求头:
request.accept = "text/javascript"
内容的提问来源于stack exchange,提问作者user1185081
相关产品推荐
相关产品推荐

