如何在 Rspec 请求中请求特定格式?

How to ask for a specific format in Rspec request?

提问人:user1185081 提问时间:11/7/2023 更新时间:11/9/2023 访问量:61

问:

我的 Playgrounds 控制器的 get_children 方法呈现特定的 javascript 模板或 json 格式的数据:

# 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

使用 Rspec 测试请求此方法时,我收到以下错误消息:.在测试中,已预先创建了操场和单子业务区:ActionController::UnknownFormat

  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

四处阅读,我找到了一些参考资料,但我没有设法让它工作。request.accept = "application/json"

如何以及在何处设置方法调用的预期输出格式?

谢谢你的帮助!

PS:RSpec版本为3.12

Ruby-on-Rails rspec

评论


答:

1赞 Alex 11/9/2023 #1
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