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

问题描述 投票:0回答:1

我的 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个回答
0
投票
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 a 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

© www.soinside.com 2019 - 2024. All rights reserved.